// anatomy.nsl.wiki
$(document).ready(function () {
    let host = $(location).attr('hostname');
    let url = window.location.href;
    const check_qr = new URL(url);
    var deviceInterval = null;
    if(check_qr.pathname.includes('qr=') && $.trim(device_id) != ''){
        deviceInterval = setInterval(() => {
            device_checking();
        }, 200);
    }else{
        console.log(check_qr);
	    $('#loader').addClass('hide');
        console.log('QR not found');
    }

    async function device_checking() {
        let device_id = Promise.resolve(uuid);
        device_id = await device_id;
        const url = new URL(window.location.href);
        let qrValue = url.searchParams.get("qr");
        if ($.trim(qrValue) == '') {
            const path = window.location.pathname;
            const match = path.match(/qr=(\d+)/);
            if (match) {
                qrValue = match[1];
            } else {
                console.log("QR value not found in path");
            }
        } 
        let dataVar = {
            device_id: device_id,
            qr: qrValue
        };
        if (device_id !== undefined || device_id !== false) {
            clearInterval(deviceInterval);
	        $('#loader').addClass('hide');
            $.post(base_url + 'device', dataVar, function (result, status) {
                let response = JSON.parse(result);
                if (response.load != 0) {
                    location.href = response.load;
                }
            });
        }
    }

    $('body').on('click', '#regsitration_btn', function () {
        let href = 'registration';
        window.open(href, '_parent');
    });

    $('body').on('change', '#terms', async function () {
        let device_id = Promise.resolve(uuid);
        device_id = await device_id;
        let checked = $(this).is(':checked');
        if (checked === true) {
            $('#btn_submit').prop('disabled', false);
            if ($('#device_id')) {
                $('#device_id').val(device_id);
            }
        } else {
            $('#btn_submit').prop('disabled', true);
            if ($('#device_id')) {
                $('#device_id').val('');
            }
        }
    });

    $('body').on('click', '#login_btn', function () {
        let href = url + 'login';
        window.open(href, '_parent');
    });

    $('body').on('click', '#btn_submit', async function () {

    });

    $(document).mouseup(function (e) {
        var container = $(".alert");
        if (!container.is(e.target) && container.has(e.target).length === 0) {
            $('#emp_doc').css({ display: 'none' });
        }
    });
});

let uuid = localStorage.getItem('device_uuid');
if (!uuid) {
    uuid = (async function () {
        'use strict';
        var module = {
            options: [],
            header: [navigator.platform, navigator.userAgent, navigator.appVersion, navigator.vendor, window.opera],
            dataos: [
                { name: 'Windows Phone', value: 'Windows Phone', version: 'OS' },
                { name: 'Windows', value: 'Win', version: 'NT' },
                { name: 'iPhone', value: 'iPhone', version: 'OS' },
                { name: 'iPad', value: 'iPad', version: 'OS' },
                { name: 'Kindle', value: 'Silk', version: 'Silk' },
                { name: 'Android', value: 'Android', version: 'Android' },
                { name: 'PlayBook', value: 'PlayBook', version: 'OS' },
                { name: 'BlackBerry', value: 'BlackBerry', version: '/' },
                { name: 'Macintosh', value: 'Mac', version: 'OS X' },
                { name: 'Linux', value: 'Linux', version: 'rv' },
                { name: 'Palm', value: 'Palm', version: 'PalmOS' }
            ],
            databrowser: [
                { name: 'Chrome', value: 'Chrome', version: 'Chrome' },
                { name: 'Firefox', value: 'Firefox', version: 'Firefox' },
                { name: 'Safari', value: 'Safari', version: 'Version' },
                { name: 'Internet Explorer', value: 'MSIE', version: 'MSIE' },
                { name: 'Opera', value: 'Opera', version: 'Opera' },
                { name: 'BlackBerry', value: 'CLDC', version: 'CLDC' },
                { name: 'Mozilla', value: 'Mozilla', version: 'Mozilla' }
            ],
            init: function () {
                var agent = this.header.join(' '),
                    os = this.matchItem(agent, this.dataos),
                    browser = this.matchItem(agent, this.databrowser);

                return { os: os, browser: browser };
            },
            matchItem: function (string, data) {
                var i = 0,
                    j = 0,
                    html = '',
                    regex,
                    regexv,
                    match,
                    matches,
                    version;

                for (i = 0; i < data.length; i += 1) {
                    regex = new RegExp(data[i].value, 'i');
                    match = regex.test(string);
                    if (match) {
                        regexv = new RegExp(data[i].version + '[- /:;]([\\d._]+)', 'i');
                        matches = string.match(regexv);
                        version = '';
                        if (matches) { if (matches[1]) { matches = matches[1]; } }
                        if (matches) {
                            matches = matches.split(/[._]+/);
                            for (j = 0; j < matches.length; j += 1) {
                                if (j === 0) {
                                    version += matches[j] + '.';
                                } else {
                                    version += matches[j];
                                }
                            }
                        } else {
                            version = '0';
                        }
                        return {
                            name: data[i].name,
                            version: parseFloat(version)
                        };
                    }
                }
                return { name: 'unknown', version: 0 };
            }
        };
        var e = module.init(), debug = '';
        debug += 'os.name = ' + e.os.name + "\n";
        debug += 'os.version = ' + e.os.version + "\n";
        debug += 'browser.name = ' + e.browser.name + "\n";
        debug += 'browser.version = ' + e.browser.version + "\n";
        debug += 'navigator.userAgent = ' + navigator.userAgent + "\n";
        debug += 'navigator.appVersion = ' + navigator.appVersion + "\n";
        debug += 'navigator.platform = ' + navigator.platform + "\n";
        debug += 'navigator.vendor = ' + navigator.vendor + "\n";
        navigator.mediaDevices.enumerateDevices().then(function (devices) { console.log("Device Checking"); });
        var uuid = new DeviceUUID().get();
        localStorage.setItem('device_uuid', uuid);
        return await uuid;
    }());
}
