$(function () {
    try {
        if (typeof chrome !== 'undefined' && chrome.runtime && chrome.runtime.getManifest) {
            $('#login_crx_version').text(chrome.runtime.getManifest().version);
        }
    } catch (err) { /* ignore */ }

    chrome.runtime.sendMessage({ action: 'get_storage', data: ['5uf_host'] }, function (response) {
        if (!response) {
            alert('chrome.storage.local初始化失败！');
            return false;
        }
        var vpn_5uf_host = response['5uf_host'];
        var alterPwdUrl = vpn_5uf_host + '/alter_config_pwd';
        $('#find_pwd').attr('href', vpn_5uf_host + '/lostpwd');
        $('#reg').attr('href', vpn_5uf_host + '/register');
        $('#login_official_link').attr('href', vpn_5uf_host + '/');
        $('#login_compat_pwd_intro_link').attr('href', alterPwdUrl);
        $('#login_alter_config_pwd_link').attr('href', alterPwdUrl);
        $('#login_logo').attr('src', 'https://www.5ufclub.com/images/logo2.png');

        function doLogin() {
            var $username = $('#username'), $password = $('#password'), $login_btn = $('#login');
            if ($login_btn.prop('disabled')) {
                return;
            }
            $login_btn.attr('disabled', 'true').html('<i class="glyphicon glyphicon-log-in" style="margin-right: 5px;"></i>玩命加载...');
            $.ajax({
                type: 'POST',
                url: vpn_5uf_host + '/api_refresh/index/nocrypt/1/nocbase64/1',
                dataType: 'json',
                data: { username: $.trim($username.val()), password: $password.val() },
                success: function (data) {
                    if (data['code'] == 1) {
                        $.ajax({
                            type: 'POST',
                            url: vpn_5uf_host + '/api_get_webproxy_site/index/nocrypt/1/nocbase64/1',
                            dataType: 'json',
                            data: { username: $.trim($username.val()), password: $password.val() },
                            success: function (data1) {
                                if (data1['code'] == 1) {
                                    var compatPwd = data['data']['userinfo']['value'];
                                    var s_data = {
                                        '5uf_login_username': $username.val(),
                                        '5uf_login_password': compatPwd,
                                        '5uf_block_list': JSON.stringify(data1['data']['site']),
                                        '5uf_block_list_system': JSON.stringify(data1['data']['system_site']),
                                        '5uf_white_list': JSON.stringify(data1['data']['white']),
                                        '5uf_white_list_system': JSON.stringify(data1['data']['system_white']),
                                        '5uf_webproxy_version': data['data']['userinfo']['webproxy_site_version'],
                                        '5uf_user_expired': data['data']['userinfo']['expired'],
                                        '5uf_user_email': data['data']['userinfo']['email'],
                                        '5uf_user_group': data['data']['userinfo']['group'],
                                        '5uf_conn_total': data['data']['userinfo']['auth_total'],
                                        '5uf_user_status': data['data']['userinfo']['attribute'],
                                        '5uf_user_online_total': data['data']['userinfo']['online_total'],
                                        'proxy_mode': 'close'
                                    };
                                    if (data['data']['userinfo']['webproxy_pwd_ready'] === 0) {
                                        s_data['5uf_no_webproxy_pwd'] = 1;
                                        s_data['proxy_mode'] = 'close';
                                    }
                                    chrome.runtime.sendMessage({ action: 'set_storage', data: s_data }, function () {
                                        if (data['data']['userinfo']['webproxy_pwd_ready'] !== 0) {
                                            chrome.storage.local.remove('5uf_no_webproxy_pwd');
                                        }
                                        chrome.runtime.sendMessage({ action: 'set_proxy' });
                                        chrome.runtime.sendMessage({ action: 'recheck_desktop_vpn' });
                                        self.location = 'popup.html';
                                    });
                                }
                            },
                            error: function () {
                                $login_btn.removeAttr('disabled').html('<i class="glyphicon glyphicon-log-in" style="margin-right: 5px;"></i>戳我登录');
                                $('#login_error_tip_text').html('登录失败');
                                $('#login_error_tip').slideDown(600);
                            }
                        });
                    } else {
                        $login_btn.removeAttr('disabled').html('<i class="glyphicon glyphicon-log-in" style="margin-right: 5px;"></i>戳我登录');
                        $('#login_error_tip_text').html(data['msg']);
                        $('#login_error_tip').slideDown(600);
                    }
                },
                error: function () {
                    $login_btn.removeAttr('disabled').html('<i class="glyphicon glyphicon-log-in" style="margin-right: 5px;"></i>戳我登录');
                    $('#login_error_tip_text').html('网络错误，登录失败');
                    $('#login_error_tip').slideDown(600);
                }
            });
        }

        $('#login').on('click', doLogin);
        $('form').on('submit', function (e) {
            e.preventDefault();
        });
        $('#username').on('keydown', function (e) {
            if (e.key !== 'Enter' && e.keyCode !== 13) {
                return;
            }
            e.preventDefault();
            $('#password').focus();
        });
        $('#password').on('keydown', function (e) {
            if (e.key !== 'Enter' && e.keyCode !== 13) {
                return;
            }
            e.preventDefault();
            doLogin();
        });
    });
});
