/*
 * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/**
 * Following function would execute
 * when a user clicks on the list item
 * initial mode and with out select mode.
 */
function InitiateViewOption(url) {
    if ($(".select-enable-btn").text() == "Select" && !$(this).hasClass("btn")) {
        url = $(this).parent().data("url");
        $(location).attr('href', url);
    }
}

(function () {
    var cache = {};
    var validateAndReturn = function (value) {
        return (value == undefined || value == null) ? "Unspecified" : value;
    };
    Handlebars.registerHelper("deviceMap", function (device) {
        device.owner = validateAndReturn(device.owner);
        device.ownership = validateAndReturn(device.ownership);
        var arr = device.properties;
        if (arr) {
            device.properties = arr.reduce(function (total, current) {
                total[current.name] = validateAndReturn(current.value);
                return total;
            }, {});
        }
    });
})();

/*
 * Setting-up global variables.
 */
var deviceCheckbox = "#ast-container .ctrl-wr-asset .itm-select input[type='checkbox']";
var assetContainer = "#ast-container";

var deviceListing, currentUser, groupId;

/*
 * DOM ready functions.
 */
$(document).ready(function () {

    var permissionSet = {};
    $.setPermission = function (permission) {
        permissionSet[permission] = true;
    };

    $.hasPermission = function (permission) {
        return permissionSet[permission];
    };

    deviceListing = $("#device-listing");
    currentUser = deviceListing.data("current-user");

    groupId = getParameterByName("groupId");

    /* Adding selected class for selected devices */
    $(deviceCheckbox).each(function () {
        addDeviceSelectedClass(this);
    });

    /* for device list sorting drop down */
    $(".ctrl-filter-type-switcher").popover({
                                                html: true,
                                                content: function () {
                                                    return $("#content-filter-types").html();
                                                }
                                            });
});

/*
 * Add selected style class to the parent element function.
 *
 * @param checkbox: Selected checkbox
 */
function addDeviceSelectedClass(checkbox) {
    if ($(checkbox).is(":checked")) {
        $(checkbox).closest(".ctrl-wr-asset").addClass("selected device-select");
    } else {
        $(checkbox).closest(".ctrl-wr-asset").removeClass("selected device-select");
    }
}

function loadProfiles() {
    var serviceURL = "/api/device-mgt/ios/v1.0/dep/profiles";

    var columns = [
        {
            targets: 0,
            class: "remove-padding icon-only content-fill",
            data: 'namePattern',
            render: function (data, type, row, meta) {
                return '<div class="thumbnail icon viewEnabledIcon">' +
                       '<i class="square-element text fw fw-document"></i>' +
                       '</div>';
            }
        },
        {
            targets: 1,
            data: 'name',
            class: 'viewEnabledIcon',
            render: function (name, type, row, meta) {
                return '<h4>' + name + '</h4>';
            }
        },
        {
            targets: 2,
            data: 'uuid',
            class: 'remove-padding-top viewEnabledIcon'
        },
        {
            targets: 3,
            data: 'department',
            class: 'remove-padding-top viewEnabledIcon'
        },
        {
            targets: 4,
            data: 'removable',
            class: 'remove-padding-top viewEnabledIcon',
            render: function (status, type, row, meta) {
                var html;
                if (row.isRemovable) {
                    html = '<span>Enabled</span>';
                } else {
                    html = '<span>Disabled</span>';
                }
                return html;
            }
        },
        {
            targets: 5,
            data: 'mandatory',
            class: 'remove-padding-top viewEnabledIcon',
            render: function (status, type, row, meta) {
                var html;
                if (row.isMandatory) {
                    html = '<span>Enabled</span>';
                } else {
                    html = '<span>Disabled</span>';
                }
                return html;
            }
        },
        {
            targets: 6,
            data: 'action-buttons',
            class: 'text-right content-fill text-left-on-grid-view no-wrap tooltip-overflow-fix',
            render: function (status, type, row, meta) {
                var uuid = row.uuid;
                var html =
                    '<a href="javascript:void(0)" data-click-event="remove-form" class="btn padding-reduce-on-grid-view edit-profile" '
                    + '" data-devicename="' + row.name
                    + '" data-uuid="' + uuid
                    + '" data-placement="top" data-toggle="tooltip" data-original-title="Edit">'
                    + '<span class="fw-stack"><i class="fw fw-circle-outline fw-stack-2x"></i>'
                    + '<i class="fw fw-edit fw-stack-1x"></i></span>'
                    + '<span class="hidden-xs hidden-on-grid-view">Edit</span></a>';
                html +=
                    '<a href="javascript:void(0)" data-click-event="remove-form" class="btn padding-reduce-on-grid-view assign-device-to-profile-link" '
                    + 'data-uuid="' + uuid
                    + '" data-placement="top" data-toggle="tooltip" data-original-title="Assign">'
                    + '<span class="fw-stack fw-lg"><i class="fw fw-circle-outline fw-stack-2x"></i>'
                    + '<i class="fw fw-devices fw-stack-1x"></i><span class="fw-stack fw-move-right fw-move-bottom">'
                    + '<i class="fw fw-circle fw-stack-2x"></i>'
                    + '<i class="fw fw-add fw-stack-1x fw-inverse"></i></span>';
                return html;
            }
        }
    ];

    var fnCreatedRow = function (row, data, dataIndex) {

        $(row).attr('data-type', 'selectable');
        var name = htmlspecialchars(data.name);
        var uuid = htmlspecialchars(data.uuid);
        var department = htmlspecialchars(data.department);
        var removable = htmlspecialchars(data.isRemovable);
        var mandatory = htmlspecialchars(data.isMandatory);
        $.each($('td', row), function (colIndex) {
            switch (colIndex) {
                case 1:
                    $(this).attr('data-search', "Name");
                    $(this).attr('data-display', name);
                    break;
                case 2:
                    $(this).attr('data-grid-label', "UUID");
                    $(this).attr('data-search', uuid);
                    $(this).attr('data-display', uuid);
                    break;
                case 3:
                    $(this).attr('data-grid-label', "Department");
                    $(this).attr('data-search', department);
                    $(this).attr('data-display', department);
                    break;
                case 4:
                    $(this).attr('data-grid-label', "Removable");
                    $(this).attr('data-search', removable);
                    $(this).attr('data-display', removable);
                    break;
                case 5:
                    $(this).attr('data-grid-label', "Mandatory");
                    $(this).attr('data-search', mandatory);
                    $(this).attr('data-display', mandatory);
                    break;
            }
        });
    };

    function htmlspecialchars(text) {
        return jQuery('<div/>').text(text).html();
    }

    var dataFilter = function (data) {
        data = JSON.parse(data);
        var objects = [];

        $(data.profiles).each(function (index) {
            var profileContent = JSON.parse(data.profiles[index].profileContent.replace(/\&quot\;/g, '"'));
            objects.push(
                {
                    name: data.profiles[index].profileName,
                    uuid: data.profiles[index].UUID,
                    isRemovable: profileContent.is_mdm_removable,
                    department: profileContent.department,
                    isMandatory: profileContent.is_mandatory
                }
            );
        });

        var json = {
            "recordsTotal": data.count,
            "recordsFiltered": data.count,
            "data": objects
        };
        return JSON.stringify(json);
    };

    $('#profile-grid').datatables_extended_serverside_paging(
        null,
        serviceURL,
        dataFilter,
        columns,
        fnCreatedRow,
        function () {
            $(".icon .text").res_text(0.2);
            var profileGrid = $('#profile-grid');
            profileGrid.removeClass('hidden');
            $("#loading-profiles").remove();
            attachProfileEvents();
            if (profileGrid.find('.dataTables_empty')[0]) {
                $("#profile-grid_wrapper").css("display", "none");
                $("#profile-ast-container").css("display", "block");
            } else {
                $("#profile-ast-container").css("display", "none");
            }
        }, {
            "placeholder": "Search By Profile Name",
            "searchKey": "name"
        }
    );

    $(deviceCheckbox).click(function () {
        addDeviceSelectedClass(this);
    });
}

function loadDevices(searchType, searchParam) {
    var serviceURL = "/api/device-mgt/ios/v1.0/dep/devices";

    var columns = [
        {
            targets: 0,
            class: "remove-padding icon-only content-fill",
            data: 'namePattern',
            render: function (data, type, row, meta) {
                return '<div class="thumbnail icon viewEnabledIcon">' +
                       '<i class="square-element text fw fw-apple"></i>' +
                       '</div>';
            }
        },
        {
            targets: 1,
            data: 'serial',
            class: 'viewEnabledIcon',
            render: function (name, type, row, meta) {
                return '<h4>' + row.serial + '</h4>';
            }
        },
        {
            targets: 2,
            data: 'model',
            class: 'viewEnabledIcon',
            render: function (name, type, row, meta) {
                return '<span>' + row.model + '</span>';
            }
        },
        {
            targets: 3,
            data: 'username',
            class: 'remove-padding-top viewEnabledIcon',
            render: function (name, type, row, meta) {
                return '<span>' + row.username + '</span>';
            }
        },
        {
            targets: 4,
            data: 'profileName',
            class: 'remove-padding-top viewEnabledIcon',
            render: function (name, type, row, meta) {
                return '<span>' + row.profileName + '</span>';
            }
        },
        {
            targets: 5,
            data: 'status',
            class: 'remove-padding-top viewEnabledIcon',
            render: function (status, type, row, meta) {
                var html;
                switch (status) {
                    case 'assigned' :
                        html = '<span><i class="fw fw-success icon-success"></i> Assigned</span>';
                        break;
                    case 'empty' :
                        html = '<span><i class="fw fw-warning icon-info"></i> Empty</span>';
                        break;
                    case 'pushed' :
                        html = '<span><i class="fw fw-remove icon-info"></i> Blocked</span>';
                        break;
                    case 'removed' :
                        html = '<span><i class="fw fw-delete icon-danger"></i> Removed</span>';
                        break;
                }
                return html;
            }
        },
        {
            targets: 6,
            data: 'needBasicAuth',
            class: 'remove-padding-top viewEnabledIcon',
            render: function (status, type, row, meta) {
                var html;
                if (row.needBasicAuth) {
                    html = '<span>Yes</span>';
                } else {
                    html = '<span>No</span>';
                }
                return html;
            }
        },
        {
            targets: 7,
            data: 'agentRequired',
            class: 'remove-padding-top viewEnabledIcon',
            render: function (status, type, row, meta) {
                var html;
                if (row.agentRequired) {
                    html = '<span>Yes</span>';
                } else {
                    html = '<span>No</span>';
                }
                return html;
            }
        },
        {
            targets: 7,
            data: 'action-buttons',
            class: 'text-right content-fill text-left-on-grid-view no-wrap tooltip-overflow-fix',
            render: function (status, type, row, meta) {
                var serial = row.serial;
                var model = row.model;
                var profile = row.profileName;
                var profileUpdatedTime = row.profileUpdatedTime;
                var username = row.username;
                var userUpdatedTime = row.userUpdatedTime;
                var status = row.status;
                var loginRequired = row.needBasicAuth;
                var agentRequired = row.agentRequired;
                var html =
                    '<a href="javascript:void(0)" data-click-event="remove-form" class="btn padding-reduce-on-grid-view info-device-to-user-link" '
                    + ' onclick="showDeviceInfo(\'' + serial + '\',\'' + model + '\',\'' + username + '\',\'' + userUpdatedTime + '\',\''
                    + profile + '\',\'' + profileUpdatedTime + '\',\'' + status + '\',' + loginRequired + ',' + agentRequired
                    + ')" data-placement="top" data-toggle="tooltip" data-original-title="Enrollment Info">'
                    + '<span class="fw-stack"><i class="fw fw-circle-outline fw-stack-2x"></i>'
                    + '<i class="fw fw-view fw-stack-1x"></i></span>';
                html +=
                    '<a href="javascript:void(0)" data-click-event="remove-form" class="btn padding-reduce-on-grid-view edit-device-to-user-link" '
                    + 'data-serial="' + serial
                    + '" data-placement="top" data-toggle="tooltip" data-original-title="Edit Enrollment">'
                    + '<span class="fw-stack fw-lg"><i class="fw fw-circle-outline fw-stack-2x"></i>'
                    + '<i class="fw fw-user fw-stack-1x"></i><span class="fw-stack fw-move-right fw-move-bottom">'
                    + '<i class="fw fw-circle fw-stack-2x"></i>'
                    + '<i class="fw fw-edit fw-stack-1x fw-inverse"></i></span>';
                if(profile === "N/A"){
                    html +=
                        '<a href="javascript:void(0)" data-click-event="remove-form" class="btn padding-reduce-on-grid-view add-device-to-profile-link" '
                        + 'data-serial="' + serial
                        + '" data-placement="top" data-toggle="tooltip" data-original-title="Assign DEP Profile">'
                        + '<span class="fw-stack fw-lg"><i class="fw fw-circle-outline fw-stack-2x"></i>'
                        + '<i class="fw fw-document fw-stack-1x"></i><span class="fw-stack fw-move-right fw-move-bottom">'
                        + '<i class="fw fw-circle fw-stack-2x"></i>'
                        + '<i class="fw fw-add fw-stack-1x fw-inverse"></i></span>';
                }else{
                    html +=
                        '<a href="javascript:void(0)" data-click-event="remove-form" class="btn padding-reduce-on-grid-view remove-device-to-profile-link" '
                        + 'data-serial="' + serial
                        + '" data-placement="top" data-toggle="tooltip" data-original-title="Remove DEP Profile">'
                        + '<span class="fw-stack fw-lg"><i class="fw fw-circle-outline fw-stack-2x"></i>'
                        + '<i class="fw fw-document fw-stack-1x"></i><span class="fw-stack fw-move-right fw-move-bottom">'
                        + '<i class="fw fw-circle fw-stack-2x"></i>'
                        + '<i class="fw fw-minus fw-stack-1x fw-inverse"></i></span>';
                }
                return html;
            }
        }
    ];

    var fnCreatedRow = function (row, data, dataIndex) {

        if (data.status != "removed") {
            $(row).attr('data-type', 'selectable');
        } else {
            $(row).attr('data-type', 'non-selectable');
        }

        $(row).attr('data-serial', htmlspecialchars(data.serial));
        $(row).attr('data-username', htmlspecialchars(data.username));
        var model = htmlspecialchars(data.model);
        var username = htmlspecialchars(data.username);
        var profileName = htmlspecialchars(data.profileName);
        var serial = htmlspecialchars(data.serial);
        var status = htmlspecialchars(data.status);
        var loginNeeded = htmlspecialchars(data.needBasicAuth);
        var agentNeeded = htmlspecialchars(data.agentRequired);
        $.each($('td', row), function (colIndex) {
            switch (colIndex) {
                case 1:
                    $(this).attr('data-search', serial);
                    $(this).attr('data-display', serial);
                    break;
                case 2:
                    $(this).attr('data-grid-label', "Model");
                    $(this).attr('data-search', model);
                    $(this).attr('data-display', model);
                    break;
                case 3:
                    $(this).attr('data-grid-label', "Username");
                    $(this).attr('data-search', username);
                    $(this).attr('data-display', username);
                    break;
                case 4:
                    $(this).attr('data-grid-label', "Profile");
                    $(this).attr('data-search', profileName);
                    $(this).attr('data-display', profileName);
                    break;
                case 5:
                    $(this).attr('data-grid-label', "Status");
                    $(this).attr('data-search', status);
                    $(this).attr('data-display', status);
                    break;
                case 6:
                    $(this).attr('data-grid-label', "Login Required");
                    $(this).attr('data-search', loginNeeded);
                    $(this).attr('data-display', loginNeeded);
                    break;
                case 7:
                    $(this).attr('data-grid-label', "Agent Required");
                    $(this).attr('data-search', agentNeeded);
                    $(this).attr('data-display', agentNeeded);
                    break;
            }
        });
    };

    function htmlspecialchars(text) {
        return jQuery('<div/>').text(text).html();
    }

    var dataFilter = function (data) {
        data = JSON.parse(data);
        var objects = [];

        $(data.devices).each(function (index) {
            if (!data.devices[index].username) {
                data.devices[index].username = "N/A";
            }
            if (!data.devices[index].depProfileName) {
                data.devices[index].depProfileName = "N/A";
            }
            objects.push(
                {
                    serial: data.devices[index].serial,
                    username: data.devices[index].username,
                    userUpdatedTime: data.devices[index].deviceAssignedTime,
                    model: data.devices[index].model,
                    profileName: data.devices[index].depProfileName,
                    profileUpdatedTime: data.devices[index].profileAssignTime,
                    status: data.devices[index].status,
                    needBasicAuth: data.devices[index].needBasicAuth,
                    agentRequired: data.devices[index].agentRequired
                }
            );
        });

        var json = {
            "recordsTotal": data.count,
            "recordsFiltered": data.count,
            "data": objects
        };
        return JSON.stringify(json);
    };

    $('#device-grid').datatables_extended_serverside_paging(
        null,
        serviceURL,
        dataFilter,
        columns,
        fnCreatedRow,
        function () {
            $(".icon .text").res_text(0.2);
            var deviceGrid = $('#device-grid');
            deviceGrid.removeClass('hidden');
            $("#loading-content").remove();
            attachDeviceEvents();
            if (deviceGrid.find('.dataTables_empty')[0]) {
                $("#device-grid_wrapper").css("display", "none");
                $("#empty-ast-container").css("display", "block");
            } else {
                $("#empty-ast-container").css("display", "none");
            }
        }, {
            "placeholder": "Search By Serial",
            "searchKey": "serial"
        }
    );

    $(deviceCheckbox).click(function () {
        addDeviceSelectedClass(this);
    });
}

function openCollapsedNav() {
    $('.wr-hidden-nav-toggle-btn').addClass('active');
    $('#hiddenNav').slideToggle('slideDown', function () {
        if ($(this).css('display') == 'none') {
            $('.wr-hidden-nav-toggle-btn').removeClass('active');
        }
    });
}


/*
 * DOM ready functions.
 */
$(document).ready(function () {
    function generateOrgMagic() {
        var text = "";
        var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

        for (var i = 0; i < 10; i++) {
            text += possible.charAt(Math.floor(Math.random() * possible.length));
        }

        return text;
    }

    function syncLoop(failCount, moreToFollow, cursor) {
        var syncDevicesAPI = "/api/device-mgt/ios/v1.0/dep/devices/sync?limit=100";

        if (moreToFollow) {
            syncDevicesAPI = "/api/device-mgt/ios/v1.0/dep/devices/sync?limit=100&cursor=" + cursor;
        }
        var contentType = "application/json";
        var acceptType = "application/json";
        invokerUtil.get(
            syncDevicesAPI,
            function (data, textStatus, jqXHR) {
                if (jqXHR.status == 200 && data) {
                    var payload = JSON.parse(data);
                    moreToFollow = (payload["more_to_follow"] === "true");
                    cursor = payload["cursor"];
                    if (moreToFollow) {
                        setTimeout(function () {
                            syncLoop(0, moreToFollow, cursor)
                        }, 500);
                    } else {
                        $(modalPopupContent).html($('#sync-devices-window-success').html());
                        location.reload();
                    }
                }
            }, function (jqXHR) {
                failCount++;
                if (failCount < 3) {
                    setTimeout(function () {
                        syncLoop(failCount, moreToFollow, cursor)
                    }, 100);
                } else {
                    $(modalPopupContent).html($('#sync-devices-window-error').html());
                    return;
                }
            }, contentType, acceptType);
    }


    $(".trigger-sync").click(function () {

        $(modalPopupContent).html($('#sync-devices-window').html());
        showPopup();

        setTimeout(function () {
            syncLoop(0)
        }, 2000);
    });

    $(".add-profile").click(function () {

        $(modalPopupContent).html($('#add-profile-window').html());
        showPopup();

        var checkboxes = document.querySelectorAll('input.subOption');
        var checkall = document.getElementById('skip');

        for (var i = 0; i < checkboxes.length; i++) {
            checkboxes[i].onclick = function () {
                var checkedCount = document.querySelectorAll('input.subOption:checked').length;
                checkall.checked = checkedCount > 0;
                checkall.indeterminate = checkedCount > 0 && checkedCount < checkboxes.length;
            }
        }

        checkall.onclick = function () {
            for (var i = 0; i < checkboxes.length; i++) {
                checkboxes[i].checked = this.checked;
            }
        };

        var mdmRemovableCheckbox = document.getElementById("mdm-removable");

        mdmRemovableCheckbox.checked = true;
        mdmRemovableCheckbox.disabled = true;

        $('#is-supervised').change(function () {
            if (!document.getElementById("is-supervised").checked) {
                mdmRemovableCheckbox.disabled = true;
                mdmRemovableCheckbox.checked = true;
            } else {
                mdmRemovableCheckbox.disabled = false;
            }
        });

        $("a#add-profile-link").click(function () {
            var profileName = $("#profile-name").val();
            var url = $("#url").val();
            var isSupervised = document.querySelector("#is-supervised").checked;
            var mdmRemovable = document.querySelector("#mdm-removable").checked;
            var isMandatory = document.querySelector("#is-mandatory").checked;
            var department = $("#department").val();
            var orgMagic = Math.floor((Math.random() * 1800000000000) + 1000000000000);
            var supportPhone = $("#sup-phone").val();
            var supportEmail = $("#sup-email").val();
            var anchorCerts = document.getElementById("anchor-certs").value;
            var appleIdCheck = document.querySelector("#id-check").checked;
            var biometricCheck = document.querySelector("#biometric-check").checked;
            var diagnosticCheck = document.querySelector("#diagnostic-check").checked;
            var displayToneCheck = document.querySelector("#display-tone-check").checked;
            var locationCheck = document.querySelector("#location-check").checked;
            var passcodeCheck = document.querySelector("#passcode-check").checked;
            var paymentCheck = document.querySelector("#payment-check").checked;
            var privacyCheck = document.querySelector("#privacy-check").checked;
            var restoreCheck = document.querySelector("#restore-check").checked;
            var siriCheck = document.querySelector("#siri-check").checked;
            var tosCheck = document.querySelector("#tos-check").checked;
            var zoomCheck = document.querySelector("#zoom-check").checked;
            var moveAndroidCheck = document.querySelector("#move-check").checked;
            var homeSensitivityCheck = document.querySelector("#homeSensitivity-check").checked;
            var watchMigrationCheck = document.querySelector("#watchMigration-check").checked;

            var errorMsgWrapper = "#add-profile-error-msg";
            var errorMsg = "#add-profile-error-msg span";
            if (!profileName) {
                $(errorMsg).text("Profile name is mandatory. It cannot be empty.");
                $(errorMsgWrapper).removeClass("hidden");
            } else if (!url) {
                $(errorMsg).text("URL is mandatory. It cannot be empty.");
                $(errorMsgWrapper).removeClass("hidden");
            } else {
                var newProfilePayload = {};
                var skip = [];
                var devices = [];
                newProfilePayload["profile_name"] = unescape((profileName));
                newProfilePayload["url"] = unescape((url));
                newProfilePayload["is_supervised"] = unescape((isSupervised));
                newProfilePayload["is_mandatory"] = unescape((isMandatory));
                newProfilePayload["is_mdm_removable"] = unescape((mdmRemovable));
                if (department) {
                    newProfilePayload["department"] = unescape((department));
                }
                newProfilePayload["org_magic"] = unescape((orgMagic));
                if (supportPhone) {
                    newProfilePayload["support_phone_number"] = unescape((supportPhone));
                }
                if (supportEmail) {
                    newProfilePayload["support_email_address"] = unescape((supportEmail));
                }
                if (anchorCerts) {
                    var anchorCertsArraySplit = anchorCerts.split(",");
                }
                if (appleIdCheck) {
                    skip.push("AppleID");
                }
                if (biometricCheck) {
                    skip.push("Biometric");
                }
                if (diagnosticCheck) {
                    skip.push("Diagnostics");
                }
                if (displayToneCheck) {
                    skip.push("DisplayTone");
                }
                if (locationCheck) {
                    skip.push("Location");
                }
                if (passcodeCheck) {
                    skip.push("Passcode");
                }
                if (paymentCheck) {
                    skip.push("Payment");
                }
                if (privacyCheck) {
                    skip.push("Privacy");
                }
                if (restoreCheck) {
                    skip.push("Restore");
                }
                if (siriCheck) {
                    skip.push("Siri");
                }
                if (tosCheck) {
                    skip.push("TOS");
                }
                if (zoomCheck) {
                    skip.push("Zoom");
                }
                if (moveAndroidCheck) {
                    skip.push("Android");
                }
                if (homeSensitivityCheck) {
                    skip.push("HomeButtonSensitivity");
                }
                if (watchMigrationCheck) {
                    skip.push("WatchMigration");
                }
                newProfilePayload["devices"] = devices;
                newProfilePayload["anchor_certs"] = anchorCertsArraySplit;
                newProfilePayload["skip_setup_items"] = skip;

                var addProfileAPI = "/api/device-mgt/ios/v1.0/dep/devices/profile";
                var contentType = "application/json";
                invokerUtil.post(
                    addProfileAPI,
                    newProfilePayload,
                    function (data, textStatus, jqXHR) {
                        if (jqXHR.status == 200 && data) {
                            $(modalPopupContent).html($('#add-profile-success-content').html());
                            $("#add-profile-success-link").click(function () {
                                hidePopup();
                            });
                        }
                    }, function (jqXHR) {
                        if (jqXHR.status == 400) {
                            $(errorMsg).text("Unable to add Profile to DEP");
                            $(errorMsgWrapper).removeClass("hidden");
                        } else {
                            var response = JSON.parse(jqXHR.responseText).message;
                            $(errorMsg).text(response);
                            $(errorMsgWrapper).removeClass("hidden");
                        }
                    }, contentType
                );
                location.reload();
            }
        });

        $("a#cancel-link").click(function () {
            hidePopup();
        });
    });

    /* Adding selected class for selected devices */
    $(deviceCheckbox).each(function () {
        addDeviceSelectedClass(this);
    });

    var permissionList = $("#permission").data("permission");
    for (var key in permissionList) {
        if (permissionList.hasOwnProperty(key)) {
            $.setPermission(key);
        }
    }

    loadDevices();
    loadProfiles();

    /* for device list sorting drop down */
    $(".ctrl-filter-type-switcher").popover({
                                                html: true,
                                                content: function () {
                                                    return $("#content-filter-types").html();
                                                }
                                            });

    /* for data tables*/
    $('[data-toggle="tooltip"]').tooltip();

    $("[data-toggle=popover]").popover();

    $(".ctrl-filter-type-switcher").popover({
                                                html: true,
                                                content: function () {
                                                    return $('#content-filter-types').html();
                                                }
                                            });

    $('#nav').affix({offset: {top: $('header').height()}});

    //Hide the search by device-name input
    $("input[placeholder='Top-Device-Name-Search']").hide();
});

var modalPopup = ".modal";
var modalPopupContainer = modalPopup + " .modal-content";
var modalPopupContent = modalPopup + " .modal-content";
var body = "body";

/*
 * set popup maximum height function.
 */
function setPopupMaxHeight() {
    $(modalPopupContent).css('max-height', ($(body).height() - ($(body).height() / 100 * 30)));
    $(modalPopupContainer).css('margin-top', (-($(modalPopupContainer).height() / 2)));
}

/*
 * show popup function.
 */
function showPopup() {
    $(modalPopup).modal('show');
}

/*
 * hide popup function.
 */
function hidePopup() {
    $(modalPopupContent).html("");
    $(modalPopupContent).removeClass("operation-data");
    $(modalPopup).modal('hide');
    $('body').removeClass('modal-open').css('padding-right', '0px');
    $('.modal-backdrop').remove();
}

function markAlreadyAssignedGroups(deviceId, deviceType) {
    var successCallback = function (data, textStatus, xhr) {
        data = JSON.parse(data);
        if (xhr.status == 200) {
            if (data.length > 0) {
                var selectedValues = [];
                for (var i = 0; i < data.length; i++) {
                    if (data[i].owner != "wso2.system.user") {
                        selectedValues.push(data[i].id);
                    }
                }
                $("#groups").val(selectedValues).trigger("change");
            }
        } else {
            displayErrors(xhr);
        }
    };

    invokerUtil.get("/api/device-mgt/v1.0/groups/device?deviceId=" + deviceId + "&deviceType=" + deviceType,
        successCallback, function (message) {
            displayErrors(message);
        });
}

/**
 * Following functions should be triggered after AJAX request is made.
 */
function attachDeviceEvents() {

    // profile-device-modal-content
    $("a.add-devices-to-profile-link").click(function () {
        addDevicesToProfile(null, getSelectedDevices());
    });

    // profile-device-modal-content
    $("a.remove-devices-to-profile-link").click(function () {
        removeDevicesToProfile(getSelectedDevices());
    });

    $("a.remove-device-to-profile-link").click(function () {
        removeDevicesToProfile([$(this).data('serial')]);
    });

    $("a.add-device-to-profile-link").click(function () {
        addDevicesToProfile(null, [$(this).data('serial')]);
    });

    /**
     * Following click function would execute
     * when a user clicks on "Add to Group" link
     * on Device Management page in WSO2 devicemgt Console.
     */
    $("a.add-devices-to-user-link").click(function () {
        addDevicesToUser(getSelectedDevices());
    });

    $("a.edit-device-to-user-link").click(function () {
        addDevicesToUser([$(this).data('serial')]);
    });
}

/**
 * Triiggered when view DEP device button clicked
 * @param serial
 * @param model
 * @param username
 * @param userUpdatedTime
 * @param profile
 * @param profileUpdatedTime
 * @param status
 * @param loginRequired
 * @param agentRequired
 */
function showDeviceInfo(serial, model, username, userUpdatedTime, profile, profileUpdatedTime, status, loginRequired, agentRequired) {
    $(modalPopupContent).html($('#device-info-modal-content').html());
    $("#view-serial").val(serial);
    $("#view-model").val(model);
    var usernameDetails = username;
    if (usernameDetails !== "N/A") {
        usernameDetails += " (" + formatDate(new Date(userUpdatedTime)) + ")";
    }
    $("#view-user").val(usernameDetails);
    var profileDetails = profile;
    if (profileDetails !== "N/A") {
        profileDetails += " (" + formatDate(new Date(profileUpdatedTime)) + ")";
    }
    $("#view-profile").val(profileDetails);
    $("#view-status").val(status);
    if (loginRequired) {
        $("#view-login-required").prop('checked', true);
    } else {
        $("#view-login-required").prop('checked', false);
    }
    if (agentRequired) {
        $("#view-agent-required").prop('checked', true);
    } else {
        $("#view-agent-required").prop('checked', false);
    }
    showPopup();
}

function formatDate(d) {
    var hours = d.getHours();
    var minutes = d.getMinutes();
    var ampm = hours >= 12 ? 'pm' : 'am';
    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    minutes = minutes < 10 ? '0'+minutes : minutes;
    var strTime = hours + ':' + minutes + ampm;
    return d.getDate() + "-" + (d.getMonth()+1) + "-" + d.getFullYear() + "  " + strTime;
}

/**
 * Following functions should be triggered after AJAX request is made.
 */
function attachProfileEvents() {
    /**
     * Following click function would execute
     * when a user clicks on "Remove" link
     * on Device Management page in WSO2 MDM Console.
     */
    $("a.edit-devices-to-profile-link").click(function () {
        //edit profile code here
    });

    $("a.assign-device-to-profile-link").click(function () {
        var uuid = $(this).data('uuid');
        if (!uuid) {
            $(modalPopupContent).html($('#no-device-selected').html());
            $("a#no-device-selected-link").click(function () {
                hidePopup();
            });
            showPopup();
            return;
        }
        addDevicesToProfile(uuid, null);
    });

    $(".edit-profile").click(function () {
        var uuid = $(this).data("uuid");
        if (!uuid) {
            return;
        }
        var serviceUrl = "/api/device-mgt/ios/v1.0/dep/profile/" + uuid;
        invokerUtil.get(
            serviceUrl,
            function (data, textStatus, jqXHR) {
                if (jqXHR.status === 200 && data) {
                    $(modalPopupContent).html($('#add-profile-window').html());
                    showPopup();

                    var checkboxes = document.querySelectorAll('input.subOption');
                    var checkall = document.getElementById('skip');

                    for (var i = 0; i < checkboxes.length; i++) {
                        checkboxes[i].onclick = function () {
                            var checkedCount = document.querySelectorAll('input.subOption:checked').length;
                            checkall.checked = checkedCount > 0;
                            checkall.indeterminate = checkedCount > 0 && checkedCount < checkboxes.length;
                        }
                    }

                    checkall.onclick = function () {
                        for (var i = 0; i < checkboxes.length; i++) {
                            checkboxes[i].checked = this.checked;
                        }
                    };

                    document.getElementById("mdm-removable").checked = true;
                    document.getElementById("mdm-removable").disabled = true;

                    $('#is-supervised').change(function () {
                        $('#is-supervised').change(function () {
                            if (!document.getElementById("is-supervised").checked) {
                                document.getElementById("mdm-removable").disabled = true;
                                document.getElementById("mdm-removable").checked = true;
                            } else {
                                document.getElementById("mdm-removable").disabled = false;
                            }
                        });
                    });

                    $('#add-profile-link').html("Update");

                    if (data) {
                        data = JSON.parse(data);
                        $("#profile-name").val(data.profile_name);
                        $("#url").val(data.url);
                        if (data.is_supervised) {
                            $("#is-supervised").prop('checked', true);
                        }
                        if (data.is_mandatory) {
                            $("#is-mandatory").prop('checked', true);
                        }
                        if (data.is_mdm_removable) {
                            $("#mdm-removable").prop('checked', true);
                        }
                        if (data.department) {
                            $("#department").val(data.department);
                        }
                        $("#sup-phone").val(data.support_phone_number);
                        $("#sup-email").val(data.support_email_address);
                        if (data.anchor_certs) {
                            $("#anchor-certs").val(data.anchor_certs.join(","));
                        }
                        var orgMagic = data.org_magic;

                        for (var i = 0; i < data.skip_setup_items.length; i++) {
                            var item = data.skip_setup_items[i];
                            if (item === "AppleID") {
                                $("#id-check").prop('checked', true);
                            } else if (item === "Biometric") {
                                $("#biometric-check").prop('checked', true);
                            } else if (item === "Diagnostics") {
                                $("#diagnostic-check").prop('checked', true);
                            } else if (item === "DisplayTone") {
                                $("#display-tone-check").prop('checked', true);
                            } else if (item === "Location") {
                                $("#location-check").prop('checked', true);
                            } else if (item === "Passcode") {
                                $("#passcode-check").prop('checked', true);
                            } else if (item === "Payment") {
                                $("#payment-check").prop('checked', true);
                            } else if (item === "Privacy") {
                                $("#privacy-check").prop('checked', true);
                            } else if (item === "Restore") {
                                $("#restore-check").prop('checked', true);
                            } else if (item === "Siri") {
                                $("#siri-check").prop('checked', true);
                            } else if (item === "TOS") {
                                $("#tos-check").prop('checked', true);
                            } else if (item === "Zoom") {
                                $("#zoom-check").prop('checked', true);
                            } else if (item === "Android") {
                                $("#move-check").prop('checked', true);
                            } else if (item === "HomeButtonSensitivity") {
                                $("#homeSensitivity-check").prop('checked', true);
                            } else if (item === "WatchMigration") {
                                $("#watchMigration-check").prop('checked', true);
                            }
                        }
                    }

                    $("a#add-profile-link").click(function () {
                        var profileName = $("#profile-name").val();
                        var url = $("#url").val();
                        var isSupervised = document.querySelector("#is-supervised").checked;
                        var mdmRemovable = document.querySelector("#mdm-removable").checked;
                        var isMandatory = document.querySelector("#is-mandatory").checked;
                        var department = $("#department").val();
                        // var orgMagic = Math.floor((Math.random() * 1800000000000) + 1000000000000);
                        var supportPhone = $("#sup-phone").val();
                        var supportEmail = $("#sup-email").val();
                        var anchorCerts = document.getElementById("anchor-certs").value;
                        var appleIdCheck = document.querySelector("#id-check").checked;
                        var biometricCheck = document.querySelector("#biometric-check").checked;
                        var diagnosticCheck = document.querySelector("#diagnostic-check").checked;
                        var displayToneCheck = document.querySelector("#display-tone-check").checked;
                        var locationCheck = document.querySelector("#location-check").checked;
                        var passcodeCheck = document.querySelector("#passcode-check").checked;
                        var paymentCheck = document.querySelector("#payment-check").checked;
                        var privacyCheck = document.querySelector("#privacy-check").checked;
                        var restoreCheck = document.querySelector("#restore-check").checked;
                        var siriCheck = document.querySelector("#siri-check").checked;
                        var tosCheck = document.querySelector("#tos-check").checked;
                        var zoomCheck = document.querySelector("#zoom-check").checked;
                        var moveCheck = document.querySelector("#move-check").checked;
                        var homeSensitivityCheck = document.querySelector("#homeSensitivity-check").checked;
                        var watchMigrationCheck = document.querySelector("#watchMigration-check").checked;

                        var errorMsgWrapper = "#add-profile-error-msg";
                        var errorMsg = "#add-profile-error-msg span";
                        if (!profileName) {
                            $(errorMsg).text("Profile name is mandatory. It cannot be empty.");
                            $(errorMsgWrapper).removeClass("hidden");
                        } else if (!url) {
                            $(errorMsg).text("URL is mandatory. It cannot be empty.");
                            $(errorMsgWrapper).removeClass("hidden");
                        } else {
                            var editProfilePayload = {};
                            var skip = [];
                            var devices = [];
                            editProfilePayload["profile_name"] = unescape((profileName));
                            editProfilePayload["url"] = unescape((url));
                            editProfilePayload["is_supervised"] = unescape((isSupervised));
                            editProfilePayload["is_mandatory"] = unescape((isMandatory));
                            editProfilePayload["is_mdm_removable"] = unescape((mdmRemovable));
                            if (department) {
                                editProfilePayload["department"] = unescape((department));
                            }
                            editProfilePayload["org_magic"] = unescape((orgMagic));
                            if (supportPhone) {
                                editProfilePayload["support_phone_number"] = unescape((supportPhone));
                            }
                            if (supportEmail) {
                                editProfilePayload["support_email_address"] = unescape((supportEmail));
                            }
                            if (anchorCerts) {
                                var anchorCertsArraySplit = anchorCerts.split(",");
                            }
                            if (appleIdCheck) {
                                skip.push("AppleID");
                            }
                            if (biometricCheck) {
                                skip.push("Biometric");
                            }
                            if (diagnosticCheck) {
                                skip.push("Diagnostics");
                            }
                            if (displayToneCheck) {
                                skip.push("DisplayTone");
                            }
                            if (locationCheck) {
                                skip.push("Location");
                            }
                            if (passcodeCheck) {
                                skip.push("Passcode");
                            }
                            if (paymentCheck) {
                                skip.push("Payment");
                            }
                            if (privacyCheck) {
                                skip.push("Privacy");
                            }
                            if (restoreCheck) {
                                skip.push("Restore");
                            }
                            if (siriCheck) {
                                skip.push("Siri");
                            }
                            if (tosCheck) {
                                skip.push("TOS");
                            }
                            if (zoomCheck) {
                                skip.push("Zoom");
                            }
                            if (moveCheck) {
                                skip.push("Android");
                            }
                            if (homeSensitivityCheck) {
                                skip.push("HomeButtonSensitivity");
                            }
                            if (watchMigrationCheck) {
                                skip.push("WatchMigration");
                            }
                            editProfilePayload["devices"] = devices;
                            editProfilePayload["anchor_certs"] = anchorCertsArraySplit;
                            editProfilePayload["skip_setup_items"] = skip;

                            var editProfileAPI = "/api/device-mgt/ios/v1.0/dep/devices/profile/" + uuid;
                            var contentType = "application/json";
                            invokerUtil.put(
                                editProfileAPI,
                                editProfilePayload,
                                function (data, textStatus, jqXHR) {
                                    if (jqXHR.status == 200 && data) {
                                        $(modalPopupContent).html($('#edit-profile-success-content').html());
                                        $("#add-profile-success-link").click(function () {
                                            hidePopup();
                                        });
                                    }
                                }, function (jqXHR) {
                                    if (jqXHR.status == 400) {
                                        $(errorMsg).text("Unable to add Profile to DEP");
                                        $(errorMsgWrapper).removeClass("hidden");
                                    } else {
                                        var response = JSON.parse(jqXHR.responseText).message;
                                        $(errorMsg).text(response);
                                        $(errorMsgWrapper).removeClass("hidden");
                                    }
                                }, contentType
                            );
                        }
                    });

                    $("a#cancel-link").click(function () {
                        hidePopup();
                    });
                }
            }, function (jqXHR) {

            });
    });
}

function addDevicesToProfile(uuid, serials) {
    $(modalPopupContent).html($('#profile-device-modal-content').html());
    if (uuid) {
        $("#profile-details").hide();
    } else {
        $("#profile-details").show();
    }
    if (serials && serials.length > 0) {
        $("#profile-to-device").hide();
    } else {
        $("#profile-to-device").show();
    }
    showPopup();

    $("a#profile-device-assign-link").click(function () {
        if (!uuid) {
            uuid = $("#profile-uuid").val();
        }
        if (!serials) {
            serials = $('#device-serial').val().split(",");
        }
        serviceURL = "/api/device-mgt/ios/v1.0/dep/devices/assign-profile";
        var payload = {
            "profile_uuid": uuid,
            "devices": serials
        };
        invokerUtil.post(serviceURL, payload, function (data) {
            $(modalPopupContent).html($('#profile-associate-device-200-content').html());
            setTimeout(function () {
                hidePopup();
                location.reload(false);
            }, 2000);
        }, function (jqXHR) {
            displayDeviceErrors(jqXHR);
        });
    });

    $("a#profile-device-cancel-link").click(function () {
        hidePopup();
    });
}

function removeDevicesToProfile(serials) {
    $(modalPopupContent).html($('#remove-profile-modal-content').html());
    showPopup();

    $("a#remove-profile-yes-link").click(function () {
        serviceURL = "/api/device-mgt/ios/v1.0/dep/devices/remove-profile";
        var payload = serials;
        invokerUtil.post(serviceURL, payload, function (data) {
            $(modalPopupContent).html($('#remove-profile-200-content').html());
            setTimeout(function () {
                hidePopup();
                location.reload(false);
            }, 2000);
        }, function (jqXHR) {
            displayDeviceErrors(jqXHR);
        });
    });

    $("a#remove-profile-cancel-link").click(function () {
        hidePopup();
    });
}

function addDevicesToUser(deviceSerials) {
    if (deviceSerials.length === 0) {
        $(modalPopupContent).html($('#no-device-selected').html());
        $("a#no-device-selected-link").click(function () {
            hidePopup();
        });
        showPopup();
        return;
    }

    var alreadyAssigned = false;
    var thisTable = $(".DTTT_selected").closest('.dataTables_wrapper').find('.dataTable').dataTable();
    thisTable.api().rows().every(function () {
        if ($(this.node()).hasClass('DTTT_selected') && $(thisTable.api().row(this).node()).data('username')) {
            alreadyAssigned = true;
        }
    });

    if (alreadyAssigned) {
        $("a#user-add-link").html("Save");
    }
    $(modalPopupContent).html($('#user-device-modal-content').html());
    showPopup();

    $("a#user-add-link").click(function () {
        var userName = $('#username').val();

        var isLoginRequired = $('#isLoginRequired').is(":checked");
        var isAgentRequired = $('#isAgentRequired').is(":checked");
        serviceURL = "/api/device-mgt/ios/v1.0/dep/devices/assign-user";
        var payload = {
            "serial": deviceSerials,
            "username": userName,
            "requireBasicAuth": isLoginRequired,
            "requireAgentInstall": isAgentRequired
        };
        invokerUtil.post(serviceURL, payload, function (data) {
            $(modalPopupContent).html($('#user-associate-device-200-content').html());
            setTimeout(function () {
                hidePopup();
                location.reload(false);
            }, 2000);
        }, function (jqXHR) {
            displayDeviceErrors(jqXHR);
        });
    });

    $("a#group-device-cancel-link").click(function () {
        hidePopup();
    });
}

function removeDevices(deviceIdentifiers) {
    var serviceURL = "/api/device-mgt/v1.0/devices/type/" + deviceIdentifiers[0].type + "/id/" +
                     deviceIdentifiers[0].id;
    invokerUtil.delete(serviceURL, function (message) {
        if (deviceIdentifiers.length > 1) {
            deviceIdentifiers.shift();
            removeDevices(deviceIdentifiers);
        } else {
            $(modalPopupContent).html($('#remove-device-200-content').html());
            setTimeout(function () {
                hidePopup();
                location.reload(false);
            }, 2000);
        }
    }, function (jqXHR) {
        displayDeviceErrors(jqXHR);
    });
}

function displayDeviceErrors(jqXHR) {
    showPopup();
    if (jqXHR.status == 400) {
        $(modalPopupContent).html($('#device-400-content').html());
        $("a#device-400-link").click(function () {
            hidePopup();
        });
    } else if (jqXHR.status == 403) {
        $(modalPopupContent).html($('#device-403-content').html());
        $("a#device-403-link").click(function () {
            hidePopup();
        });
    } else if (jqXHR.status == 409) {
        $(modalPopupContent).html($('#device-409-content').html());
        $("a#device-409-link").click(function () {
            hidePopup();
        });
    } else {
        $(modalPopupContent).html($('#device-unexpected-error-content').html());
        $("a#device-unexpected-error-link").click(function () {
            hidePopup();
        });
        console.log("Error code: " + jqXHR.status);
    }
}

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

/*
 * Function to get selected devices.
 */
function getSelectedDevices() {
    var deviceList = [];
    var thisTable = $(".DTTT_selected").closest('.dataTables_wrapper').find('.dataTable').dataTable();
    thisTable.api().rows().every(function () {
        if ($(this.node()).hasClass('DTTT_selected')) {
            deviceList.push(
                $(thisTable.api().row(this).node()).data('serial')
            );
        }
    });

    return deviceList;
}
