function uiAlert(msg) {
    window.alert(msg != null ? String(msg) : '');
}

function logout () {
    const remove_key = [
        '5uf_error_list',
        '5uf_block_list',
        '5uf_block_list_system',
        '5uf_white_list',
        '5uf_white_list_system',
        '5uf_login_username',
        '5uf_login_password',
        '5uf_user_expired',
        '5uf_user_email',
        '5uf_user_group',
        '5uf_user_online_total',
        '5uf_conn_total',
        '5uf_user_status',
        '5uf_webproxy_version',
        '5uf_desktop_vpn_conflict',
        '5uf_no_webproxy_pwd'
    ];
    chrome.runtime.sendMessage({ action: 'remove_storage', data: remove_key }, (response) => {
        chrome.proxy.settings.set({ value: { mode: 'system' }, scope: 'regular' }, () => {
            if (chrome.runtime.lastError) {
                chrome.proxy.settings.clear({ scope: 'regular' });
            }
            self.location='login.html';
        });
    });
    //chrome.action.setBadgeText({text:''});
    //chrome.action.setTitle({title:'无忧府VPN '});
    
}
function open_option(url,is_app) {
    //console.log("open_options: " + url);
    var d, options_url;
   // d = $q['defer']();
    options_url = chrome.runtime.getURL(url);
    chrome.tabs.query({
        url: options_url
    }, function(tabs) {
        var props, url, _ref;
        var urlParser = document.createElement('a');
        var hash = null;
        url = hash ? (urlParser.href = ((_ref = tabs[0]) != null ? _ref.url : void 0) || options_url, urlParser.hash = hash, urlParser.href) : options_url;
        if (tabs.length > 0) {
            props = {
                active: true
            };
            if (hash) {
                props.url = url;
            }
            chrome.tabs.update(tabs[0].id, props);
        } else {
            chrome.tabs.create({
                url: url
            });
        }
        return true;
    });
    return false;
};

function subString(str, len, hasDot)  {
    var newLength = 0;
    var newStr = "";
    var chineseRegex = /[^\x00-\xff]/g;
    var singleChar = "";
    var strLength = str.replace(chineseRegex,"**").length;
    for(var i = 0;i < strLength;i++)
    {
        singleChar = str.charAt(i).toString();
        if(singleChar.match(chineseRegex) != null)
        {
            newLength += 2;
        }
        else
        {
            newLength++;
        }
        if(newLength > len)
        {
            break;
        }
        newStr += singleChar;
    }

    if(hasDot && strLength > len)
    {
        newStr += "...";
    }
    return newStr;
}

function intro_slide_to(id){
    var left = 0-(id-1) * 692;
    //console.log(left);
    $("#intro_screen_content").animate({marginLeft:left},500);
}


function init_server_list(){
    //加载服务器列表
    chrome.runtime.sendMessage({ action: 'get_storage', data: ['5uf_host', '5uf_login_username', '5uf_login_password', '5uf_server_selected'] }, function (response) {
        if (!response || !response['5uf_host']) {
            $('#now_node_selected').text('配置加载失败');
            uiAlert('无法读取站点配置，请尝试重新登录。');
            return;
        }
        $.ajax({
            type : 'POST',
            url : response['5uf_host']+'/api_server_list/index/nocrypt/1/nocbase64/1/from/super_vpn',
            dataType : 'json',
            data : {username:response['5uf_login_username'], password:response['5uf_login_password']},
            success: function(data){
                if (data['code']==1 && data['data'] && data['data']['server']) {
                    var server_list = [], list_html = '';
                    var server_selected = response['5uf_server_selected'];
                    if (server_selected == null) {
                        $("#now_node_selected").text('未选择线路');
                    }
                    var server_selected = response['5uf_server_selected']
                    var is_selected = false;
                    $('[name="server_cell"]').remove();
                    for (var p in data['data']['server']) {
                        if (server_selected == null && data['data']['server'][p]['recommend'] == 1 && !is_selected) {
                            chrome.runtime.sendMessage({ action: 'set_storage', data: {
                                "5uf_server_selected":  data['data']['server'][p]['id'],
                                "5uf_server_selected_host": data['data']['server'][p]['name'],
                                "5uf_server_selected_port": data['data']['server'][p]['webproxy_port'],
                            }}, function () {
                                chrome.runtime.sendMessage({ action: 'set_proxy' });
                                is_selected = true;
                            });
                        }
    
                        if(data['data']['server'][p]['vpn'].indexOf("https") >= 0){
                            server_list.push(data['data']['server'][p]);
                            if (data['data']['server'][p]['max_online'] <= 0) {
                                var pr = 0
                            } else {
                                var pr = parseInt(data['data']['server'][p]['online'])/parseInt(data['data']['server'][p]['max_online']);
                                pr=pr.toFixed(3);
                                pr=pr*100;
                                pr=pr.toFixed(1);
                            }
                            //uiAlert('online:'+data['data']['server'][p]['online']+'  max_online'+data['data']['server'][p]['max_online']);
    
                            list_html += '<li name="server_cell" class="profile custom-profile ng-scope'+(data['data']['server'][p]['id'] == server_selected ? ' active' : '')+'" server_id="'+data['data']['server'][p]['id']+'" server_host="'+data['data']['server'][p]['name']+'" server_port="'+data['data']['server'][p]['webproxy_port']+'"><a href="#" role="button" class="ng-scope" ><span class="ng-binding ng-isolate-scope"><span class="ng-isolate-scope"><span  class="" style="color: rgb(250, 175, 58);"><img src="'+(data['data']['server'][p]['icon'].length>0 ? response['5uf_host']+'/images/plugin_icon/'+data['data']['server'][p]['icon'] : 'img/null.png')+'"> <div style="width:60px; height:20px; position: absolute; margin-left: 150px; margin-top: -24px;">    <div class="progress" pname="'+data['data']['server'][p]['net']+'">     <div class="progress-bar  progress-bar-warning progress-bar-striped active" role="progressbar" aria-valuenow="'+pr+'" aria-valuemin="0" aria-valuemax="100" style="font-size:8px;padding-left:10px; text-shadow: 0px 0px 0px ;text-shadow:0px 0px 1px #000; color:#fff;; width: '+pr+'%">     '+pr+'% </div>     </div>     </div>'+(data['data']['server'][p]['recommend'] == 1 ? '<div class="recommend"></div>' : '')+'</span></span><span class="ing" style="color:red;display:none">[切换中...] </span>'+data['data']['server'][p]['net']+'</span></a></li>';
                            if (data['data']['server'][p]['id'] == server_selected) {
                                $("#now_node_selected").text(subString(data['data']['server'][p]['net'], 22, true));
                                $("#now_node_selected").parent().find(".glyphicon-signal").hide();
                            }
                        }else{
                            //data['data']['server'].remove(p);
                        }
                    }
    
                    $('#custom_profile_before').after(list_html);
                    chrome.runtime.sendMessage({ action: 'set_storage', data: {
                        "5uf_server_list": JSON.stringify(server_list)
                    }});
                } else {
                    $('#now_node_selected').text('加载失败');
                    uiAlert('服务器列表加载失败');
                }
            },
            error: function () {
                $('#now_node_selected').text('网络错误');
            }
        });
    });
    
}

function disable_conflict(){
  chrome.management.getAll(function(e) {
    var list = [];
    var my_id = chrome.runtime.id;
    for(var i in e)
    {
      var id = e[i].id;
      var name = e[i].name;
      if (id==my_id)
      {
        continue;
      }
      for (var j in e[i].permissions)
      {
        if(e[i].permissions[j] == "proxy")
        {
          chrome.management.setEnabled(id,false,function(e){
          });
          break;
        }
      }
    }
    chrome.tabs.reload();
    //background.refresh();
    window.close();
  });

}

$(function(){

    if (!window._5uf_desktop_storage_listener) {
        window._5uf_desktop_storage_listener = true;
        chrome.storage.onChanged.addListener(function (changes, area) {
            if (area !== 'local') {
                return;
            }
            if (changes['5uf_desktop_vpn_conflict'] || changes['5uf_no_webproxy_pwd']) {
                window.location.reload();
            }
        });
    }
    chrome.runtime.sendMessage({ action: 'recheck_desktop_vpn' });

    chrome.runtime.sendMessage({ action: 'get_storage', data: ['5uf_host', '5uf_server_selected', 'crx_version', '5uf_host_2', 'proxy_mode', '5uf_web_host', '5uf_user_status', '5uf_login_username', '5uf_login_password', '5uf_user_group', '5uf_user_expired', '5uf_user_online_total', '5uf_conn_total', '5uf_desktop_vpn_conflict', '5uf_no_webproxy_pwd'] }, function (response) {
        if (!response) {
            alert('chrome.storage.local初始化失败！');
            return false;
        }
        $('#svpn_logo').parent().attr('href', response['5uf_host_2']);
        $('#version_bottom').attr('href', response['5uf_host_2']).text(response['crx_version']);
        $('#charge').attr('href', response['5uf_host_2']+'/buy');
        var user_status = response['5uf_user_status'];
        if (user_status == 'Disable') {
            $('#status').attr('class', 'text-danger').html('不可用');
        } else if (user_status == 'inactive' || user_status == 'Inactive') {
            $('#status').attr('class', 'text-warning').html('流量超额');
        }
        if (typeof(response['5uf_login_username']) == 'string') {
            $('#svpn_username').html(response['5uf_login_username']);
            var now = Math.round(new Date().getTime()/1000);

            $('#svpn_group').html(response['5uf_user_group'] || '');
            var expired = parseInt(response['5uf_user_expired'], 10);
            if (!isFinite(expired) || expired <= 0 || expired < now) {
                $('#svpn_days').html('<span style="color:red">已过期</span>');
                $('#status').attr('class', 'text-danger').html('不可用');
            } else {
                var day = (expired - now) / (3600*24);
                $('#svpn_days').html((isFinite(day) ? day.toFixed(2) : '--') + '天');
                if (day < 7) {
                    $('#tip_remain').show(600);
                    $('#now_domain1').height('110');
                }
            }
            var online_total = response['5uf_user_online_total'];
            var conn_total = response['5uf_conn_total'];
            $('#online_total').html(online_total);
            $('#conn_total').html(conn_total);
            if (parseInt(online_total) > conn_total) {
                $('#conn_tip').attr('class', 'text-danger').html('<strong>已经超出连接数,请<a target="_blank" href="'+response['5uf_web_host']+'/buy'+'">升级</a></strong>');
            }

        } else {
            self.location='login.html';
            return;
        }
        if (response['5uf_desktop_vpn_conflict']) {
            $('#first_run').hide();
            $('#not_controllable').hide();
            $('#controllable').hide();
            $('#no_webproxy_pwd_panel').hide();
            $('#desktop_vpn_conflict_panel').show();
            $('#desktop_vpn_recheck_btn').off('click').on('click', function () {
                chrome.runtime.sendMessage({ action: 'recheck_desktop_vpn' }, function () {
                    window.location.reload();
                });
            });
            return;
        }
        if (response['5uf_no_webproxy_pwd']) {
            $('#first_run').hide();
            $('#not_controllable').hide();
            $('#controllable').hide();
            $('#desktop_vpn_conflict_panel').hide();
            $('#no_webproxy_pwd_panel').show();
            $('#no_webproxy_pwd_recheck_btn').off('click').on('click', function () {
                chrome.runtime.sendMessage({ action: 'run_check_online_now' }, function () {
                    window.setTimeout(function () {
                        window.location.reload();
                    }, 1200);
                });
            });
            return;
        }
        $('#no_webproxy_pwd_panel').hide();
        $('#desktop_vpn_conflict_panel').hide();
        window.setTimeout(function(){
            $('#tongji').html(window.trace_code);
        }, 100);

        $('#open_options_btn').off('click').on('click', function (e) {
            e.preventDefault();
            open_option('options.html');
            return false;
        });

        //名单
        init_white_list();
        init_block_list();
        //检查第一次运行（非首次引导完成后会调用 check_conflict）
        check_first_run();
            $("#intro_btn_go_step1").click(function(){
            intro_slide_to(1);
        });
        $("#intro_btn_go_step2").click(function(){
            intro_slide_to(2);
        });
        $("#intro_btn_go_step3").click(function(){
            intro_slide_to(3);
        });

        $(".intro_btn_finsh").click(function() {
            $("#first_run").animate({width:240,opacity:0},500,"",function(){
                $("#not_controllable").hide();
                $("#controllable").show();
                chrome.runtime.sendMessage({ action: 'set_storage', data: {
                    "5uf_first_run": 0
                }});
                $("#first_run").hide();
                check_conflict();
            });
        });

        //取消关闭其他代理插件
        $("#not_disable_other").click(function(){
            uiAlert("不禁用其他插件可能会无法使用无忧府VPN！");
            $("#controllable").show();
            $("#not_controllable").hide();
        });
        //关闭其他代理插件
        $("#disable_other").click(function(){
            disable_conflict();
        });
        
        init_server_list();
        $('.popup-menu-nav').on('click', 'li[name="server_cell"]', function() {
            chrome.runtime.sendMessage({ action: 'set_storage', data: {
                "5uf_server_selected": $(this).attr('server_id'),
                "5uf_server_selected_host": $(this).attr('server_host'),
                "5uf_server_selected_port": $(this).attr('server_port')
            }});
            chrome.runtime.sendMessage({ action: 'set_proxy' });
            var li = $(this).find('.ing');
            li.show();
            $.ajax({
                type : 'POST',
                timeout : window.ajax_timeout*1000,
                dataType : 'json',
                data: {'now':response['5uf_server_selected'], 'user':response['5uf_login_username'], 'pass':response['5uf_login_password']},
                url : response['5uf_host']+'/plugin_close_conn',
                success: function(data){
                    if (data['code'] == 1) {
                        chrome.runtime.sendMessage({ action: 'test_url' }, (resp) => {
                            console.log(resp);
                            if (resp.success) {
                                $.ajax({
                                    type : 'POST',
                                    url : response['5uf_host']+'/api_refresh/index/nocrypt/1/nocbase64/1',
                                    dataType : 'json',
                                    data : {username:response['5uf_login_username'], password:response['5uf_login_password']},
                                    success: function(data){
                                        if (data['code']==1) {
                                            chrome.runtime.sendMessage({ action: 'set_storage', data: {
                                                "5uf_user_expired": data['data']['userinfo']['expired'],
                                                "5uf_user_email": data['data']['userinfo']['email'],
                                                "5uf_user_group": data['data']['userinfo']['group'],
                                                "5uf_user_online_total": data['data']['userinfo']['online_total'],
                                                "5uf_conn_total": data['data']['userinfo']['auth_total'],
                                                "5uf_user_status": data['data']['userinfo']['attribute'],
                                            }});

                                            $('#online_total').text(data['data']['userinfo']['online_total']);
                                            $('#conn_total').text(data['data']['userinfo']['auth_total']);
                                        }
                                    }
                                });
                                
                                chrome.runtime.sendMessage({ action: 'refresh_tab' });
                                li.hide();
                                window.close();
                            } else {
                                li.hide();
                                alert('可能切换失败');
                            }
                        });
                    } else {
                        li.hide();
                        alert('切换失败');
                    }
    
    
                },
                error: function () {
                    li.hide();
                    uiAlert('切换失败');
                }
            });
        });

        //判断模式
        var proxy_mode = response['proxy_mode'];
        console.log('运行模式：'+proxy_mode);
        if (proxy_mode == 'all') {
            $(".btn_mode").removeClass("btn-success");
            $(".btn_mode").addClass("btn-default");
            $("#btn_mode_all").removeClass("btn-default");
            $("#btn_mode_all").addClass("btn-success");
            init_server_list();
        }
        if (proxy_mode == 'require') {
            $(".btn_mode").removeClass("btn-success");
            $(".btn_mode").addClass("btn-default");
            $("#btn_mode_require").removeClass("btn-default");
            $("#btn_mode_require").addClass("btn-success");
            init_server_list();
        }
        if (proxy_mode == 'close') {
            $(".btn_mode").removeClass("btn-success");
            $(".btn_mode").addClass("btn-default");
            $("#btn_mode_close").removeClass("btn-default");
            $("#btn_mode_close").addClass("btn-success");
            $(".node_list_tip").hide();
            $("#btn_select_node").hide();
        }

        //点击展示服务器列表
        $("#btn_select_node").click(function(){
            $("#main_control").hide();
            $("#profile_list").show();
            $("#open_options_btn").hide();
            $("#bottom_content").hide();
            $("#goback_btn").show();
        });
        //返回
        $("#goback_btn").click(function(){
            $("#main_control").show();
            $("#rules_list").hide();

            $("#rules_list_white").hide();
            $("#profile_list").hide();
            $("#open_options_btn").show();
            $("#goback_btn").hide();
            $("#goback_btn_white").hide();
            $("#bottom_content").show();
        });
        //规则列表
        $("#btn_select_mode").click(function(){
            $("#main_control").hide();
            $("#rules_list").show();
            $("#open_options_btn").hide();
            $("#bottom_content").hide();
            $("#goback_btn").show();
            init_block_list();
        });

        //规则列表
        $("#btn_white_mode").click(function(){
            $("#main_control").hide();
            $("#rules_list_white").show();
            $("#open_options_btn").hide();
            $("#bottom_content").hide();
            $("#goback_btn").show();
            init_block_list();
        });
    });


    //加入白名单
    $("#btn_add_white_domain").click(function(){
        chrome.runtime.sendMessage({ action: 'get_storage', data: ['5uf_host', '5uf_login_username', '5uf_login_password', '5uf_white_list'] }, function (response) {
            var domain_name = $("#domain_name").text();
            if (domain_name!="" && domain_name!=undefined && domain_name.length>=3) {
                $.ajax({
                    type : 'POST',
                    url : response['5uf_host']+'/api_add_webproxy_site/index/nocrypt/1/nocbase64/1',
                    dataType : 'json',
                    data : {username:response['5uf_login_username'], password:response['5uf_login_password'], site:[domain_name], type:0},
                    success: function(data){
                        if (data['code']==1) {
                            var white_list = response['5uf_white_list'];
                            if (typeof(white_list) == 'undefined' || white_list == null) {
                                var white_list = [];
                            }
                            white_list = window.safeJsonParse(white_list, []);
                            white_list[white_list.length] = domain_name;
                            chrome.runtime.sendMessage({ action: 'set_storage', data: {'5uf_white_list': JSON.stringify(white_list)} });
                            $("#domain_add_tip").show();
                            $("#domain_add_btn").hide();
                            $("#domain_add_white_btn").hide();
                            chrome.runtime.sendMessage({ action: 'set_proxy' });
                            chrome.runtime.sendMessage({ action: 'refresh_tab' });
                            chrome.runtime.sendMessage({ action: 'set_storage', data: {
                                '5uf_block_list': JSON.stringify(data['data']['site']),
                                '5uf_webproxy_version': data['data']['version']
                            }});
                            window.setTimeout(function(){
                                window.close();
                            },500);
                        } else {
                            uiAlert(data['msg']);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus) {
                        uiAlert("网络错误，添加失败！\n status:"+XMLHttpRequest.status+', readyState:'+XMLHttpRequest.readyState+', text:'+textStatus);
                    }
                });
            } else {
                uiAlert('该网址无法加入');
            }
        });
    });


    //添加当前域名进入规则
    $("#btn_add_domain").click(function(){
        chrome.runtime.sendMessage({ action: 'get_storage', data: ['5uf_host', '5uf_login_username', '5uf_login_password', '5uf_block_list'] }, function (response) {
            var domain_name = $("#domain_name").text();
            if (domain_name!="" && domain_name!=undefined && domain_name.length>=3) {
                $.ajax({
                    type : 'POST',
                    url : response['5uf_host']+'/api_add_webproxy_site/index/nocrypt/1/nocbase64/1',
                    dataType : 'json',
                    data : {username:response['5uf_login_username'], password:response['5uf_login_password'], site:[domain_name], type:1},
                    success: function(data){
                        if (data['code']==1) {
                            var block_list = response['5uf_block_list'];
                            if (typeof(block_list) == 'undefined' || block_list == null) {
                                var block_list = [];
                            }
                            block_list = window.safeJsonParse(block_list, []);
                            block_list[block_list.length] = domain_name;
                            chrome.runtime.sendMessage({ action: 'set_storage', data: {'5uf_block_list': JSON.stringify(block_list)} });
                            $("#domain_add_tip").show();
                            $("#domain_add_btn").hide();
                            chrome.runtime.sendMessage({ action: 'set_proxy' });
                            chrome.runtime.sendMessage({ action: 'refresh_tab' });
                            chrome.runtime.sendMessage({ action: 'set_storage', data: {
                                '5uf_block_list': JSON.stringify(data['data']['site']),
                                '5uf_webproxy_version': data['data']['version']
                            }});
                            window.setTimeout(function(){
                                window.close();
                            },500);
                        } else {
                            uiAlert(data['msg']);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus) {
                        uiAlert("网络错误，添加失败！\n status:"+XMLHttpRequest.status+', readyState:'+XMLHttpRequest.readyState+', text:'+textStatus);
                    }
                });
            } else {
                uiAlert('该网址无法加入');
            }
        });
    });

    chrome.runtime.sendMessage({ action: 'get_storage', data: ['5uf_error_list'] }, function (response) {
        //页面打不开？
        var error_list = response['5uf_error_list'];
        if (error_list == null) {
            chrome.runtime.sendMessage({ action: 'set_storage', data: {
                "5uf_error_list": '{}',
            }});
            error_list = '{}';
        }
        error_list = window.safeJsonParse(error_list, {});
        if (Array.isArray(error_list)) {
            error_list = {};
        }

        chrome.tabs.query({ currentWindow: true, active: true }, function (tab) {
            
            var tabId = tab[0].id;
            
            if (typeof(error_list[tabId]) == '' || error_list[tabId] == null || error_list[tabId].length == 0) {
                $('#btn_apply_random_node').text('没有加载失败的资源');
                return;
            }
            $('#btn_apply_random_node').text('此页面检测到'+error_list[tabId].length+'个资源打开失败').attr('点击添加到列表');
            $('#btn_apply_random_node').click(function(){
                chrome.runtime.sendMessage({ action: 'get_storage', data: ['5uf_error_list', '5uf_host', '5uf_login_username', '5uf_login_password'] }, function (response) {
                    Array.prototype.unique1 = function() {
                        var n = {},r=[]; //n为hash表，r为临时数组
                        for(var i = 0; i < this.length; i++) {
                            if (!n[this[i]]) {
                                n[this[i]] = true; //存入hash表
                                r.push(this[i]); //把当前数组的当前项push到临时数组里面
                            }
                        }
                        return r;
                    }
                    var error_list = response['5uf_error_list'];
                    error_list = window.safeJsonParse(error_list, {});
                    if (Array.isArray(error_list)) {
                        error_list = {};
                    }
                    if (!error_list[tabId]) {
                        error_list[tabId] = [];
                    }
                    error_list[tabId].unique1();
                    var list = '\n';
                    //uiAlert(writeObj(error_list[tabId]));
                    //return;

                    for(var i = 0; i < error_list[tabId].length; i++) {
                        if (i == error_list[tabId].length -1) {
                            list += error_list[tabId][i];
                        } else {
                            if ((i+1)%3 == 0) {
                                list += error_list[tabId][i]+'\n';
                            } else {
                                list += error_list[tabId][i]+',  ';
                            }
                        }
                    }
                    if (!confirm("是否把一下这"+error_list[tabId].length+'个网址加入列表？'+list)) {
                        if (confirm("取消后会清空这些探测到的资源，确定继续吗？")) {
                            error_list[tabId] = [];
                            chrome.runtime.sendMessage({ action: 'set_storage', data: {
                                "5uf_error_list": JSON.stringify(error_list)
                            }});
                            $('#btn_apply_random_node').text('没有加载失败的资源').unbind('click');
                            chrome.action.setBadgeText({text:''});
                            chrome.action.setTitle({title:'无忧府VPN '});
                            return;
                        }
                        return;
                    }
                    $.ajax({
                        type : 'POST',
                        url : response['5uf_host']+'/api_add_webproxy_site/index/nocrypt/1/nocbase64/1',
                        dataType : 'json',
                        data : {username:response['5uf_login_username'], password:response['5uf_login_password'], site:error_list[tabId], type:1},
                        timeout : 30000,
                        success: function(data) {
                            if (data['code'] == 1) {
                                chrome.runtime.sendMessage({ action: 'get_storage', data: ['5uf_block_list'] }, function (response) {
                                    var block_list = response['5uf_block_list'];
                                    if (typeof (block_list) == 'undefined' || block_list == null) {
                                        var block_list = '[]';
                                        chrome.runtime.sendMessage({
                                            action: 'set_storage', data: {
                                                "5uf_block_list": block_list
                                            }
                                        });
                                    }
                                    block_list[block_list.length] = domain_name;
                                    chrome.runtime.sendMessage({
                                        action: 'set_storage', data: {
                                            "5uf_block_list": JSON.stringify(data['data']['site']),
                                            "5uf_webproxy_version": data['data']['version'],
                                        }
                                    }, function () {
                                        chrome.runtime.sendMessage({ action: 'set_proxy' });
                                    });

                                    
                                    error_list[tabId] = [];
                                    chrome.runtime.sendMessage({
                                        action: 'set_storage', data: {
                                            "5uf_error_list": JSON.stringify(error_list)
                                        }
                                    });
                                    chrome.action.setBadgeText({ text: '' });
                                    chrome.action.setTitle({ title: '无忧府VPN ' });
                                    chrome.runtime.sendMessage({ action: 'refresh_tab' });
                                    window.setTimeout(function () {
                                        window.close();
                                    }, 500);
                                });
                                
                            } else {
                                alert(data['msg']);
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            chrome.action.setBadgeText({text:''});
                            chrome.action.setTitle({title:'无忧府VPN '});
                            chrome.runtime.sendMessage({ action: 'get_storage', data: ['5uf_block_list'] }, function (response) {
                                if (XMLHttpRequest.readyState == 0 && XMLHttpRequest.readyState == 0) {
                                    var block_list = response['5uf_block_list'];
                                    if (typeof(block_list) == 'undefined' || block_list == null) {
                                        var block_list = '[]';
                                        chrome.runtime.sendMessage({ action: 'set_storage', data: {
                                            "5uf_block_list": block_list
                                        }});
                                    }
                                    block_list = window.safeJsonParse(block_list, []);
                                    var f = 0;
                                    for(var i = 0; i < error_list[tabId].length; i++) {
                                        f = 0
                                        for (var z = 0; z < block_list.length; z++) {
                                            if (block_list[z] == error_list[tabId][i]) {
                                                f == 1;
                                                break;
                                            }
                                        }
                                        if (f == 0) {
                                            block_list[block_list.length] = error_list[tabId][i];
                                        }
                                    }
                                    chrome.runtime.sendMessage({ action: 'set_storage', data: {
                                        "5uf_block_list": JSON.stringify(block_list)
                                    }}, function () {
                                        chrome.runtime.sendMessage({ action: 'set_proxy' });
                                    });
            
                                    
                                    error_list[tabId] = [];
                                    chrome.runtime.sendMessage({ action: 'set_storage', data: {
                                        "5uf_error_list": JSON.stringify(error_list)
                                    }});
                                    chrome.action.setBadgeText({text:''});
                                    chrome.action.setTitle({title:'无忧府VPN '});
                                    window.setTimeout(function(){
                                        window.close();
                                    },500);
                                    return;
                                } else {
                                    uiAlert('网络错误，添加失败');
                                }
            
                                //alert('状态码'+XMLHttpRequest.readyState+'\nhttp请求状态'+XMLHttpRequest.status+'\nhttp返回信息'+XMLHttpRequest.responseText);
                            });
                            
                        }
                    });

                })
            });
        });
    });

    //删除当前域名从规则
    $("#btn_remove_domain").click(function(){
        var domain_name = $("#domain_name").text();
        chrome.runtime.sendMessage({ action: 'get_storage', data: ['5uf_host', '5uf_block_list', '5uf_login_username', '5uf_login_password'] }, function (response) {
            $.ajax({
                type : 'POST',
                url : response['5uf_host']+'/api_del_webproxy_site/index/nocrypt/1/nocbase64/1',
                dataType : 'json',
                data : {username:response['5uf_login_username'], password:response['5uf_login_password'], site:domain_name},
                success: function(data){
                    if (data['code']==1) {
                        var block_list = response['5uf_block_list'];
                        block_list = window.safeJsonParse(block_list, []);
                        var new_block_list = [];
                        for (var i in block_list) {
                            if (block_list[i] == domain_name) {
                                continue;
                            }
                            new_block_list[new_block_list.length] = block_list[i];
                        }
                        chrome.runtime.sendMessage({ action: 'set_storage', data: {
                            "5uf_block_list": JSON.stringify(new_block_list),
                            "5uf_webproxy_version": data['data']['version'],
                            "5uf_block_list": JSON.stringify(data['data']['site'])
                        }});
                        $("#domain_add_tip").hide();
                        $("#domain_add_btn").show();
                        chrome.runtime.sendMessage({ action: 'set_proxy' });
                        chrome.runtime.sendMessage({ action: 'refresh_tab' });
                        window.setTimeout(function(){
                            //omegaTarget.refreshActivePage();
                            window.close();
                        },500);
                    } else {
                        alert(data['msg']);
                    }
                },
                error: function (XMLHttpRequest, textStatus) {
                    uiAlert("网络错误，删除失败！\n status:"+XMLHttpRequest.status+', readyState:'+XMLHttpRequest.readyState+', text:'+textStatus);
                }
            });
        })
    });


    //搜索框实时搜索
    $("#search_domain_text_input").keyup(function(){
        var text = $(this).val();
        if (text=="") {
            init_block_list();
            return;
        }
        $("#rules_list li").each(function(index,element){
            var domain = $(element).find("a").attr("title");
            if (domain.indexOf(text) != -1) {
                $(element).show();
                return;
            }
            $(element).hide();
        });
    });
    //搜索框实时搜索--白名单
    $("#search_white_domain_text_input").keyup(function(){
        var text = $(this).val();
        if (text=="") {
            init_white_list();
            return;
        }
        $("#rules_list_white li").each(function(index,element){
            var domain = $(element).find("a").attr("title");
            if (domain.indexOf(text) != -1) {
                $(element).show();
                return;
            }
            $(element).hide();
        });
    });
    //获取当前域名
    get_current_domain();

    $('#link_exit').click(function(){
        logout();
    });

    //tooltip
    $("#btn_mode_all").mouseenter(function(e){
        $(".proxy_mode_tip").hide();
        $("#proxy_tip_all").show();
        var c = chrome.extension.getBackgroundPage();
        if(c)  {
            //document.write("Clicks:" );

        }
        //uiAlert(c.background);
    });
    $("#btn_mode_require").mouseenter(function(e){
        $(".proxy_mode_tip").hide();
        $("#proxy_tip_require").show();
    });
    $("#btn_mode_close").mouseenter(function(e){
        $(".proxy_mode_tip").hide();
        $("#proxy_tip_close").show();
    });
    $(".proxy_mode_select").mouseleave(function(e){
        $(".proxy_mode_tip").hide();
    });


    //click
    $("#btn_mode_close").click(function(e){
        $("#now_domain").hide();
        $("#now_domain_liner").hide();
        chrome.runtime.sendMessage({ action: 'set_storage', data: {proxy_mode: 'close'} });
        //common.proxy_mode = common.proxy_mode_enum.DIRECT;
        $(".btn_mode").removeClass("btn-success");
        $(".btn_mode").addClass("btn-default");
        $("#btn_mode_close").removeClass("btn-default");
        $("#btn_mode_close").addClass("btn-success");
        $(".node_list_tip").hide();
        $("#btn_select_node").hide();
        chrome.runtime.sendMessage({ action: 'set_proxy' });
        //common.set_chrome_storage({"proxy_mode":common.proxy_mode},function(){common.getBackground().refresh();});
    });

    $("#btn_mode_require").click(function(e){

        $("#now_domain").show();
        $("#now_domain_liner").show();
        chrome.runtime.sendMessage({ action: 'set_storage', data: {proxy_mode: 'require'} });
        //common.proxy_mode = common.proxy_mode_enum.REQUIRE;
        $(".btn_mode").removeClass("btn-success");
        $(".btn_mode").addClass("btn-default");
        $("#btn_mode_require").removeClass("btn-default");
        $("#btn_mode_require").addClass("btn-success");
        get_current_domain();
        $(".node_list_tip").show();
        $("#btn_select_node").show();
        chrome.runtime.sendMessage({ action: 'set_proxy' });
        init_server_list();
        //common.set_chrome_storage({"proxy_mode":common.proxy_mode},function(){background.refresh();});
    });


    $("#btn_mode_all").click(function(e){
        chrome.runtime.sendMessage({ action: 'set_storage', data: {proxy_mode: 'all'} });
        //common.proxy_mode = common.proxy_mode_enum.ALL;
        $(".btn_mode").removeClass("btn-success");
        $(".btn_mode").addClass("btn-default");
        $("#btn_mode_all").removeClass("btn-default");
        $("#btn_mode_all").addClass("btn-success");
        $("#now_domain").hide();
        $("#now_domain_liner").hide();
        $(".node_list_tip").show();
        $("#btn_select_node").show();
        init_server_list();
        chrome.runtime.sendMessage({ action: 'set_proxy' });
    });
});


function del_white_domain(domain_name) {
    chrome.runtime.sendMessage({ action: 'get_storage', data: ['5uf_white_list'] }, function (response) {
        var white_list = response['5uf_white_list'];
        white_list = window.safeJsonParse(white_list, []);
        var new_white_list = [];
        for (var i in white_list) {
            if (white_list[i] == domain_name) {
                continue;
            }
            new_white_list[new_white_list.length] = white_list[i];
        }
        chrome.runtime.sendMessage({ action: 'set_storage', data: {
            "5uf_white_list": JSON.stringify(new_white_list)
        }});
        init_white_list();
        chrome.runtime.sendMessage({ action: 'set_proxy' });
        chrome.runtime.sendMessage({ action: 'refresh_tab' });
    });
        
}

function del_block_domain(domain_name) {
    chrome.runtime.sendMessage({ action: 'get_storage', data: ['5uf_block_list'] }, function (response) {
        var block_list = response['5uf_block_list'];
        block_list = window.safeJsonParse(block_list, []);
        var new_block_list = [];
        for (var i in block_list) {
            if (block_list[i] == domain_name) {
                continue;
            }
            new_block_list[new_block_list.length] = block_list[i];
        }
        chrome.runtime.sendMessage({ action: 'set_storage', data: {
            "5uf_block_list": JSON.stringify(new_block_list)
        }});

        var domain_name2 = $("#domain_name").text();
        if (domain_name2 == domain_name) {
              $("#domain_add_tip").hide();
              $("#domain_add_btn").show();
        }
        init_block_list();
        chrome.runtime.sendMessage({ action: 'set_proxy' });
        chrome.runtime.sendMessage({ action: 'refresh_tab' });
    });
}

//初始化加速规则列表
function init_white_list() {
    chrome.runtime.sendMessage({ action: 'get_storage', data: ['5uf_white_list', '5uf_host', '5uf_login_username', '5uf_login_password'] }, function (response) {
        var white_list = response['5uf_white_list'];
        white_list = window.safeJsonParse(white_list, []);
        var obj = $("#rules_list_white ul");
    
        obj.html("");
        for (var i in white_list) {
            var tmp = '<li class="profile rules_list_domain"><a href="#" role="button" title="[domain_name]" style="padding-right: 0px; margin-bottom: 5px; line-height: 30px; color: #999" ><span>[domain_name]</span><button class="btn btn-danger btn-sm btn-remove-white-domain" domain="[domain_name]" style="float: right; height: 30px;padding-top: 0px; padding-bottom: 0px; margin: 0px; font-size: 12px; padding-left: 5px; padding-right:5px; " >删除</button></a></li>';
            tmp = tmp.replace(/\[domain_name\]/g, white_list[i]);
            //uiAlert(tmp);
            obj.append(tmp);
        }
        $(".btn-remove-white-domain").click(function(){
            var domain = $(this).attr("domain");
            $.ajax({
                type : 'POST',
                url : response['5uf_host']+'/api_del_webproxy_site/index/nocrypt/1/nocbase64/1',
                dataType : 'json',
                data : {username:response['5uf_login_username'], password:response['5uf_login_password'], site:domain, type:0},
                success: function(data){
                    if (data['code']==1) {
                        chrome.runtime.sendMessage({
                            action: 'set_storage', data: {
                                "5uf_block_list": JSON.stringify(data['data']['site']),
                                "5uf_block_list_system": JSON.stringify(data['data']['system_site']),
                                "5uf_white_list": JSON.stringify(data['data']['white']),
                                "5uf_white_list_system": JSON.stringify(data['data']['system_white']),
                            }
                        });
                        del_white_domain(domain);
                        chrome.runtime.sendMessage({
                            action: 'set_storage', data: {
                                "5uf_webproxy_version": data['data']['version'],
                            }
                        });
                    } else {
                        uiAlert(data['msg']);
                    }
                },
                error: function (XMLHttpRequest, textStatus) {
                    uiAlert("网络错误，删除失败！\n status:"+XMLHttpRequest.status+', readyState:'+XMLHttpRequest.readyState+', text:'+textStatus);
                }
            });
        });
    });
}


//初始化加速规则列表
function init_block_list() {
    chrome.runtime.sendMessage({ action: 'get_storage', data: ['5uf_block_list', '5uf_host', '5uf_login_username', '5uf_login_password'] }, function (response) {
        var block_list = response['5uf_block_list'];
        block_list = window.safeJsonParse(block_list, []);
        var obj = $("#rules_list ul");
        obj.html("");
        for (var i in block_list) {
            var tmp = '<li class="profile rules_list_domain"><a href="#" role="button" title="[domain_name]" style="padding-right: 0px; margin-bottom: 5px; line-height: 30px; color: #999" ><span>[domain_name]</span><button class="btn btn-danger btn-sm btn-remove-block-domain" domain="[domain_name]" style="float: right; height: 30px;padding-top: 0px; padding-bottom: 0px; margin: 0px; font-size: 12px; padding-left: 5px; padding-right:5px; " >删除</button></a></li>';
            tmp = tmp.replace(/\[domain_name\]/g, block_list[i]);
            obj.append(tmp);
        }
        $(".btn-remove-block-domain").click(function(){
            var domain = $(this).attr("domain");
            $.ajax({
                type : 'POST',
                url : response['5uf_host']+'/api_del_webproxy_site/index/nocrypt/1/nocbase64/1',
                dataType : 'json',
                data : {username:response['5uf_login_username'], password:response['5uf_login_password'], site:domain, type:1},
                success: function(data){
                    if (data['code']==1) {
                        del_block_domain(domain);
                        chrome.runtime.sendMessage({ action: 'set_storage', data: {
                            "5uf_webproxy_version": data['data']['version'],
                            "5uf_block_list":JSON.stringify(data['data']['site'])
                        }});
                    } else {
                        uiAlert(data['msg']);
                    }
                },
                error: function () {
                    uiAlert('网络错误，删除失败！');
                }
            });
        });
    });
    
}

function base64Encode(input){
    var rv;
    rv = encodeURIComponent(input);
    rv = unescape(rv);
    rv = window.btoa(rv);
    return rv;
}
function check_first_run() {
    chrome.runtime.sendMessage({ action: 'get_storage', data: ['5uf_first_run'] }, function (response) {
        var first_run = response['5uf_first_run'];
        if (first_run == null) {
            $("#first_run").show();
            $("#not_controllable").hide();
            $("#controllable").hide();
    
        } else {
            $("#first_run").hide();
            check_conflict();
            return;
        }
    });
}


function check_conflict() {
    chrome.runtime.sendMessage({ action: 'check_proxy_conflict' }, function (result) {
        if (chrome.runtime.lastError || !result || result.error) {
            return;
        }
        if (result.blockMainUI) {
            var html = '';
            var exts = result.otherProxyExtensions || [];
            for (var i = 0; i < exts.length; i++) {
                var ext = exts[i];
                var iconUrl = (ext.icons && ext.icons[0] && ext.icons[0].url) ? ext.icons[0].url : '';
                html += '<li>' + (iconUrl ? '<img width="16" src="' + iconUrl + '" alt=""> ' : '') + ext.name + '</li>';
            }
            if (result.proxyLevel === 'controlled_by_other_extensions' && exts.length === 0) {
                html += '<li>（Chrome 显示代理由其它扩展接管；若已关闭同类扩展仍如此，请重启浏览器后再试）</li>';
            }
            $('#conflict_list').html(html);
            $('#controllable').hide();
            $('#not_controllable').show();
        } else {
            $('#not_controllable').hide();
            $('#controllable').show();
        }
    });
}



//获取当前访问的域名
function get_current_domain() {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        if (!tabs || !tabs[0] || !tabs[0].url) {
            return;
        }
        var active_tab = tabs[0]; // 当前活动标签页的信息
        var durl = /(.*?):\/\/([^\/]+)\//i;
        var tmp = active_tab.url.match(durl);
        if (!tmp || tmp.length < 3) {
            return;
        }
        var protocol = tmp[1];
        var tmp2 = tmp[2].split(".");
        var domain = "";
        if (tmp2.length >= 2) {
            var a = tmp2[tmp2.length - 2]; //com
            var b = tmp2[tmp2.length - 1]; //cn
            var c = tmp2[tmp2.length - 3]; //sina
            domain = a + "." + b;
            for (i in window.special_domain_suffix) {
                var stmp = window.special_domain_suffix[i].split(".");
                var stmp_len = stmp.length;
                if (tmp2.length > stmp_len && tmp[2].indexOf(window.special_domain_suffix[i]) != -1) {
                    domain = '';
                    for (var ii = tmp2.length - stmp_len - 1; ii < tmp2.length; ii++) {
                        domain += (tmp2[ii] + '.');
                    }
                    domain = domain.substr(0, domain.length - 1);
                    break;
                }
            }
        } else {
            domain = tmp2[tmp2.length - 1];
            protocol = "local";
        }
        if (tmp2.length == 4 && !isNaN(parseInt(tmp2[0])) && !isNaN(parseInt(tmp2[1])) && !isNaN(parseInt(tmp2[2])) && !isNaN(parseInt(tmp2[3]))) {
            var is_ok = 0;
            var regex = /[0-9]{1,3}/;
            for (var i in tmp2) {
                if (regex.test(tmp2[i])) {
                    is_ok++;
                }
            }
            domain = tmp2[0] + "." + tmp2[1] + "." + tmp2[2] + "." + tmp2[3];
        }

        $("#domain_name").text(domain);
        $(".show_domain_name").text(domain);
        chrome.runtime.sendMessage({ action: 'get_storage', data: ['proxy_mode', '5uf_block_list', '5uf_block_list_system', '', ''] }, function (response) {
            var proxy_mode = response['proxy_mode'];
            if (proxy_mode == 'require' && (protocol == "http" || protocol == "https")) {
                $("#now_domain").show();
                $("#now_domain_liner").show();
                $("#domain_add_tip").hide();
                $("#domain_add_btn").show();
                $("#profile_list").css("height", "200px");
                var block_list = response['5uf_block_list'];
                block_list = window.safeJsonParse(block_list, []);
                var block_list_system = response['5uf_block_list_system'];
                block_list_system = window.safeJsonParse(block_list_system, []);
    
                for (var i in block_list_system) {
                    if (block_list_system[i] == domain) {
    
                        $("#domain_add_tip").hide();
                        $("#domain_add_btn").hide();
                        $("#domain_add_white_btn").show();
                        break;
                    }
                }
                for (var i in block_list) {
                    if (block_list[i] == domain) {
                        $("#domain_add_tip").show();
                        $("#domain_add_btn").hide();
                        $("#domain_add_white_btn").hide();
                        break;
                    }
                }
            } else {
                $("#now_domain").hide();
                $("#now_domain_liner").hide();
            }
        });
        
    });
}