//初始化下标和title
if (localStorage.getItem('5uf_login_username') != null && localStorage.getItem('5uf_login_password') != null) {
    localStorage.setItem('5uf_error_list', JSON.stringify({}));
    chrome.browserAction.setBadgeText({text:''});
    chrome.browserAction.setTitle({title:'无忧府VPN '});
} else {
    localStorage.setItem('5uf_error_list', JSON.stringify({}));
}
window.complete = [];
localStorage.setItem('disable', 0);


chrome.webRequest.onAuthRequired.addListener(function(details){
		console.log(details);
        if (localStorage.getItem('5uf_login_username') != null) {
            console.log('认证成功');
            return {
                authCredentials: {username:localStorage.getItem('5uf_login_username'), password:localStorage.getItem('5uf_login_password')}
            };
        } else {
            console.log('无法认证');
            return {};
        }
    }, {
        urls: ['<all_urls>']
    }, ['blocking']
);

//获取域名
$.ajax({
    type : 'GET',
    url : window.find_host,
    cache : false,
    timeout : window.ajax_timeout*1000,
    success: function(data){
        if (data == null || data.length == 0 || data.substring(0, 4) != 'http') {
            data.split(/[\s\n]/);
            localStorage.setItem('5uf_host', window.pre_host);
            localStorage.setItem('5uf_web_host', window.pre_host);
            return;
        }
        localStorage.setItem('5uf_host', data);
        localStorage.setItem('5uf_web_host', window.pre_host);
        //localStorage.setItem('5uf_host', 'http://www.5uf7.com');

    },
    error: function () {
        $.ajax({
            type : 'GET',
            url : window.find_host,
            cache : false,
            timeout : window.ajax_timeout*1000,
            success: function(data){
                localStorage.setItem('5uf_host', data);
                localStorage.setItem('5uf_web_host', window.pre_host);
            },
            error: function () {
                localStorage.setItem('5uf_host', window.pre_host);
                localStorage.setItem('5uf_web_host', window.pre_host);
            },
            complete: function (XHR, TS) {
                XHR = null;
            }
        });
    },
    complete: function (XHR, TS) {
        XHR = null;
    }
});

$.ajax({
    type : 'GET',
    url : window.find_host_2,
    cache : false,
    timeout : window.ajax_timeout*1000,
    success: function(data){
        if (data == null || data.length == 0 || data.substring(0, 4) != 'http') {
            localStorage.setItem('5uf_host_2', window.pre_host);
            localStorage.setItem('5uf_web_host', window.pre_host);
            return;
        }
        localStorage.setItem('5uf_host_2', data);
        localStorage.setItem('5uf_web_host', window.pre_host);
        //localStorage.setItem('5uf_host', 'http://www.5uf7.com');

    },
    error: function () {
        $.ajax({
            type : 'GET',
            url : window.find_host_2,
            cache : false,
            timeout : window.ajax_timeout*1000,
            success: function(data){
                localStorage.setItem('5uf_host_2', data);
                localStorage.setItem('5uf_web_host', window.pre_host);
            },
            error: function () {
                localStorage.setItem('5uf_host_2', window.pre_host);
                localStorage.setItem('5uf_web_host', window.pre_host);
            },
            complete: function (XHR, TS) {
                XHR = null;
            }
        });
    },
    complete: function (XHR, TS) {
        XHR = null;
    }
});

$.ajax({
    type : 'GET',
    url : window.find_host_2,
    cache : false,
    timeout : window.ajax_timeout*1000,
    success: function(data){
        if (data == null || data.length == 0 || data.substring(0, 4) != 'http') {
            localStorage.setItem('5uf_host_2', window.pre_host);
            localStorage.setItem('5uf_web_host', window.pre_host);
            return;
        }
        localStorage.setItem('5uf_host', data);
        localStorage.setItem('5uf_web_host', window.pre_host);
        //localStorage.setItem('5uf_host', 'http://www.5uf7.com');

    },
    error: function () {
        $.ajax({
            type : 'GET',
            url : window.find_host_2,
            cache : false,
            timeout : window.ajax_timeout*1000,
            success: function(data){
                localStorage.setItem('5uf_host_2', data);
                localStorage.setItem('5uf_web_host', window.pre_host);
            },
            error: function () {
                localStorage.setItem('5uf_host_2', window.pre_host);
                localStorage.setItem('5uf_web_host', window.pre_host);
            },
            complete: function (XHR, TS) {
                XHR = null;
            }
        });
    },
    complete: function (XHR, TS) {
        XHR = null;
    }
});

//设置代理
set_proxy();

//检查更新
window.setTimeout(function(){
    $.ajax({
        type : 'GET',
        url : localStorage.getItem('5uf_host')+'/data/crx/crx_version.txt',
        cache : false,
        timeout : window.ajax_timeout*1000,
        success: function(data){
            var arr = data.split("$$");
            if (arr.length==3) {
                localStorage.setItem('5uf_web_host', 'http://'+arr[2]);
            }
            if (arr.length==3 && parseFloat(arr[0]) > window.current_version) {
                var log = arr[1].split('$');
                var log_txt = '';
                for (i=0;i<log.length;i++) {
                    log_txt += '  '+log[i]+'\n';
                }
                if (confirm('无忧府VPN检测到新版本插件，版本：'+arr[0]+'\n\n更新日志：\n'+log_txt+'\n\n 确定下载更新吗？')) {
                    var options_url = localStorage.getItem('5uf_host_2')+'/news/vpn/id/11061/';
                    //alert('open');
                    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;
                    });
                }
            }
        },
        error: function () {
        },
        complete: function (XHR, TS) {
            XHR = null
        }
    });
}, window.update_limit*1000);


//同步site
function sync_site () {
    if (localStorage.getItem('5uf_login_username') != null && localStorage.getItem('5uf_login_password') != null) {
        $.ajax({
            type : 'POST',
            url : localStorage.getItem('5uf_host')+'/api_sync_webproxy_site/index/nocrypt/1/nocbase64/1',
            dataType : 'json',
            timeout : window.ajax_timeout*1000,
            data : {username:localStorage.getItem('5uf_login_username'), password:localStorage.getItem('5uf_login_password'), version:localStorage.getItem('5uf_webproxy_version')},
            success: function(data){
                if (data['code']==1) {
                    localStorage.setItem('5uf_block_list', JSON.stringify(data['data']['site']));
                    localStorage.setItem('5uf_block_list_system', JSON.stringify(data['data']['system_site']));
                    localStorage.setItem('5uf_white_list', JSON.stringify(data['data']['white']));
                    localStorage.setItem('5uf_white_list_system', JSON.stringify(data['data']['system_white']));
                    localStorage.setItem('5uf_webproxy_version', data['data']['version']);
                    set_proxy();
                } else {

                }
            },
            error: function () {

            },
            complete: function (XHR, TS) {
                XHR = null;
                setTimeout(function () {
                    sync_site();
                }, window.site_sync_limit*1000);
            }
        });
    }
}
sync_site();

/*
setInterval(function(){
    if (localStorage.getItem('5uf_login_username') != null && localStorage.getItem('5uf_login_password') != null) {
        $.ajax({
            type : 'POST',
            url : localStorage.getItem('5uf_host')+'/api_sync_webproxy_site/index/nocrypt/1/nocbase64/1',
            dataType : 'json',
            timeout : window.ajax_timeout*1000,
            data : {username:localStorage.getItem('5uf_login_username'), password:localStorage.getItem('5uf_login_password'), version:localStorage.getItem('5uf_webproxy_version')},
            success: function(data){
                if (data['code']==1) {
                    localStorage.setItem('5uf_block_list', JSON.stringify(data['data']['site']));
                    localStorage.setItem('5uf_block_list_system', JSON.stringify(data['data']['system_site']));
                    localStorage.setItem('5uf_white_list', JSON.stringify(data['data']['white']));
                    localStorage.setItem('5uf_white_list_system', JSON.stringify(data['data']['system_white']));
                    localStorage.setItem('5uf_webproxy_version', data['data']['version']);
                    set_proxy();
                } else {

                }
            },
            error: function () {

            },
            complete: function (XHR, TS) {
                XHR = null
            }
        });
    }
}, window.site_sync_limit*1000);
*/

chrome.webRequest.onBeforeRequest.addListener(
    details => {
        //alert(localStorage.getItem('proxy_mode') != 'close');
        if (parseInt(localStorage.getItem('5uf_user_online_total')) > parseInt(localStorage.getItem('5uf_conn_total')) && localStorage.getItem('proxy_mode') != 'close') {
            chrome.tabs.update({url: chrome.runtime.getURL("block.html")});
            return { redirectUrl: chrome.runtime.getURL("block.html") };
        }
    },
    {
      urls: ["http://*/*", "https://*/*"],
      types: ["main_frame", "sub_frame"]
    }
    ,['blocking']
);

//在线连接数检查
function check_online () {
    if (localStorage.getItem('5uf_login_username') != null && localStorage.getItem('5uf_login_password') != null) {
        $.ajax({
            type : 'POST',
            url : localStorage.getItem('5uf_host')+'/api_refresh/index/nocrypt/1/nocbase64/1',
            dataType : 'json',
            timeout : window.ajax_timeout*1000,
            data : {username:localStorage.getItem('5uf_login_username'), password:localStorage.getItem('5uf_login_password')},
            success: function(data){
                if (data['code']==1) {
                    if ((parseInt(data['data']['userinfo']['online_total']) > parseInt(data['data']['userinfo']['auth_total']) || data['data']['userinfo']['attribute'] != 'Password') && localStorage.getItem('proxy_mode') != 'close') {

                        localStorage.setItem('disable', 1);
                        //alert('连接数超出限制,或状态不可用');
                        // localStorage.getItem('5uf_host')
                        // var pac =
                        // "var FindProxyForURL = function(url, host){"+
                        //     "var white_list_system = "+localStorage.getItem('5uf_white_list_system')+';'+
                        //     "for(i=0;i<white_list_system.length;i++){"+
                        //         "if (host.indexOf(white_list_system[i])!=-1){"+
                        //              "return 'DIRECT';"+
                        //         "}"+
                        //     "}"+
                        //      "return 'HTTPS "+window.disbaled_server+"';"+
                        // "}";
                        // //alert(pac);
                        // var config = {
                        //     mode: "pac_script",
                        //     pacScript: {
                        //         data: pac
                        //     }
                        // }
                        // chrome.proxy.settings.set({value: config, scope: 'regular'}, function(){});
                        return;
                    } else {
                        set_proxy();
                    }

                    localStorage.setItem('5uf_user_expired', data['data']['userinfo']['expired']);
                    localStorage.setItem('5uf_user_email', data['data']['userinfo']['email']);
                    localStorage.setItem('5uf_user_group', data['data']['userinfo']['group']);
                    localStorage.setItem('5uf_user_online_total', data['data']['userinfo']['online_total']);
                    localStorage.setItem('5uf_conn_total', data['data']['userinfo']['auth_total']);
                    localStorage.setItem('5uf_user_status', data['data']['userinfo']['attribute']);
                } else {
                    var pac =
                    "var  = function(url, host){"+
                         "return 'DIRECT';"+
                    "}";
                    //alert(pac);
                    var config = {
                        mode: "pac_script",
                        pacScript: {
                            data: pac
                        }
                    }
                    chrome.proxy.settings.set({value: config, scope: 'regular'}, function(){});
                    localStorage.removeItem('first_run');
                    localStorage.removeItem('5uf_server_list');
                    localStorage.removeItem('5uf_server_selected');
                    localStorage.removeItem('5uf_server_selected_port');
                    localStorage.removeItem('5uf_server_selected_host');
                    localStorage.removeItem('proxy_mode');
                    //localStorage.removeItem('5uf_host');
                    localStorage.removeItem('5uf_error_list');
                    localStorage.removeItem('5uf_block_list');
                    localStorage.removeItem('5uf_block_list_system');
                    localStorage.removeItem('5uf_white_list');
                    localStorage.removeItem('5uf_white_list_system');

                    localStorage.removeItem('5uf_login_username');
                    localStorage.removeItem('5uf_login_password');
                    localStorage.removeItem('5uf_user_expired');
                    localStorage.removeItem('5uf_user_email');
                    localStorage.removeItem('5uf_user_group');
                    localStorage.removeItem('5uf_user_online_total');
                    localStorage.removeItem('5uf_conn_total');
                    localStorage.removeItem('5uf_user_status');
                    localStorage.removeItem('5uf_webproxy_version');
                    chrome.browserAction.setBadgeText({text:0+''});
                    chrome.browserAction.setTitle({title:'无忧府VPN '+'未发现加载失败的资源'});
                    alert('无忧府VPN已经退出');
                }
            },
            error: function () {

            },
            complete: function (XHR, TS) {
                XHR = null;
                setTimeout(function () {
                    check_online();
                }, window.auth_limit*1000);
            }
        });
    }
}

check_online();

/*
setInterval(function(){
    if (localStorage.getItem('5uf_login_username') != null && localStorage.getItem('5uf_login_password') != null) {
        $.ajax({
            type : 'POST',
            url : localStorage.getItem('5uf_host')+'/api_refresh/index/nocrypt/1/nocbase64/1',
            dataType : 'json',
            timeout : window.ajax_timeout*1000,
            data : {username:localStorage.getItem('5uf_login_username'), password:localStorage.getItem('5uf_login_password')},
            success: function(data){
                if (data['code']==1) {
                    if ((data['data']['userinfo']['online_total'] > data['data']['userinfo']['auth_total'] || data['data']['userinfo']['attribute'] != 'Password') && localStorage.getItem('proxy_mode') != 'close') {
                        //alert('连接数超出限制,或状态不可用');
                        var pac =
                        "var FindProxyForURL = function(url, host){"+
                            "var white_list_system = "+localStorage.getItem('5uf_white_list_system')+';'+
                            "for(i=0;i<white_list_system.length;i++){"+
                                "if (host.indexOf(white_list_system[i])!=-1){"+
                                     "return 'DIRECT';"+
                                "}"+
                            "}"+
                             "return 'HTTPS renew.5ufweb.cc:443';"+
                        "}";
                        //alert(pac);
                        var config = {
                            mode: "pac_script",
                            pacScript: {
                                data: pac
                            }
                        }
                        chrome.proxy.settings.set({value: config, scope: 'regular'}, function(){});
                        return;
                    } else {
                        set_proxy();
                    }

                    localStorage.setItem('5uf_user_expired', data['data']['userinfo']['expired']);
                    localStorage.setItem('5uf_user_email', data['data']['userinfo']['email']);
                    localStorage.setItem('5uf_user_group', data['data']['userinfo']['group']);
                    localStorage.setItem('5uf_user_online_total', data['data']['userinfo']['online_total']);
                    localStorage.setItem('5uf_conn_total', data['data']['userinfo']['auth_total']);
                    localStorage.setItem('5uf_user_status', data['data']['userinfo']['attribute']);
                } else {
                    var pac =
                    "var  = function(url, host){"+
                         "return 'DIRECT';"+
                    "}";
                    //alert(pac);
                    var config = {
                        mode: "pac_script",
                        pacScript: {
                            data: pac
                        }
                    }
                    chrome.proxy.settings.set({value: config, scope: 'regular'}, function(){});
                    localStorage.removeItem('first_run');
                    localStorage.removeItem('5uf_server_list');
                    localStorage.removeItem('5uf_server_selected');
                    localStorage.removeItem('5uf_server_selected_port');
                    localStorage.removeItem('5uf_server_selected_host');
                    localStorage.removeItem('proxy_mode');
                    //localStorage.removeItem('5uf_host');
                    localStorage.removeItem('5uf_error_list');
                    localStorage.removeItem('5uf_block_list');
                    localStorage.removeItem('5uf_block_list_system');
                    localStorage.removeItem('5uf_white_list');
                    localStorage.removeItem('5uf_white_list_system');

                    localStorage.removeItem('5uf_login_username');
                    localStorage.removeItem('5uf_login_password');
                    localStorage.removeItem('5uf_user_expired');
                    localStorage.removeItem('5uf_user_email');
                    localStorage.removeItem('5uf_user_group');
                    localStorage.removeItem('5uf_user_online_total');
                    localStorage.removeItem('5uf_conn_total');
                    localStorage.removeItem('5uf_user_status');
                    localStorage.removeItem('5uf_webproxy_version');
                    chrome.browserAction.setBadgeText({text:0+''});
                    chrome.browserAction.setTitle({title:'无忧府VPN '+'未发现加载失败的资源'});
                    alert('无忧府VPN已经退出');
                }
            },
            error: function () {

            },
            complete: function (XHR, TS) {
                XHR = null
            }
        });
    }
}, window.auth_limit*1000);
*/


function getDomainFromUrl(url){
    if (url.indexOf("chrome-extension://") != -1) {
        return;
    }
	var durl = /(.*?):\/\/([^\/]+)\//i;
          var tmp = url.match(durl);
          var protocol = tmp[1];
          var tmp2 = tmp[2].split(".");
          var domain = "";
          if (tmp2.length >= 2) {
            var a = tmp2[tmp2.length - 2];
            var b = tmp2[tmp2.length - 1];
            var c = tmp2[tmp2.length - 3];
            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];
          }
		return domain;
}

function b_confirm(text) {
	return confirm(text);
}

function b_alert(text) {
	alert(text);
}

function refresh () {
	chrome.tabs.reload();
}

function setBadgeText(obj){
	chrome.browserAction.setBadgeText(obj);
}

function setTitle(obj){
	chrome.browserAction.setTitle(obj);
}


//右键
function allOnClick(info, tab) {
    if (localStorage.getItem('5uf_login_username') == null || localStorage.getItem('5uf_login_password') == null) {
        alert('请先登录');
        return;
    }
    var domain_name = getDomainFromUrl(tab.url);
    if (domain_name!="" && domain_name!=undefined && domain_name.length>=3) {
        var block_list = localStorage.getItem('5uf_block_list');
        if (typeof(block_list) == 'undefined' || block_list == null) {
            var block_list = [];
            localStorage.setItem('5uf_block_list', JSON.stringify(block_list));
        }

        block_list = localStorage.getItem('5uf_block_list');
        block_list = JSON.parse(block_list);
        for (var i in block_list) {
            if (block_list[i] == domain_name) {
                alert('已经添加到列表');
                return;
            }
        }
        $.ajax({
            type : 'POST',
            url : localStorage.getItem('5uf_host')+'/api_add_webproxy_site/index/nocrypt/1/nocbase64/1',
            dataType : 'json',
            timeout : window.ajax_timeout*1000,
            data : {username:localStorage.getItem('5uf_login_username'), password:localStorage.getItem('5uf_login_password'), site:domain_name, type:1},
            success: function(data){
                if (data['code']==1) {
                    var block_list = localStorage.getItem('5uf_block_list');
                    if (typeof(block_list) == 'undefined' || block_list == null) {
                        var block_list = [];
                        localStorage.setItem('5uf_block_list', JSON.stringify(block_list));
                    }

                    block_list = localStorage.getItem('5uf_block_list');
                    block_list = JSON.parse(block_list);


                    localStorage.setItem('5uf_block_list', JSON.stringify(data['data']['site']));
                    localStorage.setItem('5uf_webproxy_version', data['data']['version']);
                    alert('已经添加到列表');
                    set_proxy();
                    chrome.extension.getBackgroundPage().refresh();
                } else {
                    alert(data['msg']);
                }
            },
            error: function (XMLHttpRequest, textStatus) {
                alert("网络错误，添加失败！\n"+"status:"+XMLHttpRequest.status+', readyState:'+XMLHttpRequest.readyState+', text:'+textStatus);
            },
            complete: function (XHR, TS) {
                XHR = null
            }
        });
        return;
    } else {
        alert('链接无效');
    }
    alert('此链接无法加入');
}

//链接右键
function genericOnClick(info, tab) {
    if (localStorage.getItem('5uf_login_username') == null || localStorage.getItem('5uf_login_password') == null) {
        alert('请先登录');
        return;
    }

    var domain_name = getDomainFromUrl(info.linkUrl);
    if (domain_name!="" && domain_name!=undefined && domain_name.length>=3) {

        var block_list = localStorage.getItem('5uf_block_list');
        if (typeof(block_list) == 'undefined' || block_list == null) {
            var block_list = [];
            localStorage.setItem('5uf_block_list', JSON.stringify(block_list));
        }

        block_list = localStorage.getItem('5uf_block_list');
        block_list = JSON.parse(block_list);
        for (var i in block_list) {
            if (block_list[i] == domain_name) {
                alert('已经添加到列表');
                return;
            }
        }
        $.ajax({
            type : 'POST',
            url : localStorage.getItem('5uf_host')+'/api_add_webproxy_site/index/nocrypt/1/nocbase64/1',
            dataType : 'json',
            timeout : window.ajax_timeout*1000,
            data : {username:localStorage.getItem('5uf_login_username'), password:localStorage.getItem('5uf_login_password'), site:domain_name, type:1},
            success: function(data){
                if (data['code']==1) {
                    var block_list = localStorage.getItem('5uf_block_list');
                    if (typeof(block_list) == 'undefined' || block_list == null) {
                        var block_list = [];
                        localStorage.setItem('5uf_block_list', JSON.stringify(block_list));
                    }

                    block_list = localStorage.getItem('5uf_block_list');
                    block_list = JSON.parse(block_list);


                    localStorage.setItem('5uf_block_list', JSON.stringify(data['data']['site']));
                    localStorage.setItem('5uf_webproxy_version', data['data']['version']);
                    alert('已经添加到列表');
                    set_proxy();
                    chrome.extension.getBackgroundPage().refresh();
                } else {
                    alert(data['msg']);
                }
            },
            error: function () {
                alert('网络错误，添加失败！');
            },
            complete: function (XHR, TS) {
                XHR = null
            }
        });
        return;
    } else {
        alert('链接无效');
    }
    alert('此链接无法加入');
}

/*
var link = chrome.contextMenus.create({"title": "将此链接加入列表","contexts":["link"],"onclick":genericOnClick});
var selection = chrome.contextMenus.create({"title": "将此页面加入列表","contexts":["all"],"onclick":allOnClick});

chrome.webRequest.onCompleted.addListener(function (a) {
    if (localStorage.getItem('5uf_login_username') == null && localStorage.getItem('5uf_login_password') == null) {
        return;
    }
    //获得域名
    var domain_name = getDomainFromUrl(a.url);
    if (domain_name=="" || domain_name==undefined || domain_name.length<3) {
        return ;
    }
    if (a.url.indexOf("chrome-extension") != -1) {
		return ;
	}
	if (a.url.indexOf("192.") != -1) {
		return ;
	}
	if (a.url.indexOf("127.") != -1) {
		return ;
	}
	if (a.url.indexOf("10.") != -1) {
		return ;
	}
	if (a.url.indexOf("100.") != -1) {
		return ;
	}
	if (a.url.indexOf("localhost") != -1) {
		return ;
	}
    for (var i in  window.complete) {
        if ( window.complete[i] == domain_name) {
            return;
        }
    }
    window.complete.push(domain_name);
    //alert( window.complete);
}, {
    urls: ["<all_urls>"]
});

chrome.webRequest.onErrorOccurred.addListener(function (a) {
    //alert(a.tabId);
    if (localStorage.getItem('5uf_login_username') == null && localStorage.getItem('5uf_login_password') == null) {
        return;
    }
    //获得域名
    var domain_name = getDomainFromUrl(a.url);
    if (domain_name=="" || domain_name==undefined || domain_name.length<3) {
        return ;
    }

    //错误列表
    var error_list = localStorage.getItem('5uf_error_list');
    if (typeof(error_list) == 'undefined' || error_list == null) {
        var error_list = {};
        localStorage.setItem('5uf_error_list', JSON.stringify(error_list));
    }
    var error_list = localStorage.getItem('5uf_error_list');
    error_list = JSON.parse(error_list);

    //加速列表
    var block_list = localStorage.getItem('5uf_block_list');
    if (typeof(block_list) == 'undefined' || block_list == null) {
        var block_list = [];
        localStorage.setItem('5uf_block_list', JSON.stringify(block_list));
    }
    var block_list = localStorage.getItem('5uf_block_list');
    block_list = JSON.parse(block_list);

    //通用加速列表
    var block_list_system = localStorage.getItem('5uf_block_list_system');
    if (typeof(block_list_system) == 'undefined' || block_list_system == null) {
        var block_list_system = [];
        localStorage.setItem('5uf_block_list_system', JSON.stringify(block_list_system));
    }
    var block_list_system = localStorage.getItem('5uf_block_list_system');
    block_list_system = JSON.parse(block_list_system);


    if (a.url.indexOf("chrome-extension") != -1) {
		return ;
	}
	if (a.url.indexOf("192.") != -1) {
		return ;
	}
	if (a.url.indexOf("127.") != -1) {
		return ;
	}
	if (a.url.indexOf("10.") != -1) {
		return ;
	}
	if (a.url.indexOf("100.") != -1) {
		return ;
	}
	if (a.url.indexOf("localhost") != -1) {
		return ;
	}
    var tabId = a.tabId, tab_key = 'tab_'+tabId;

    if (a.error.indexOf("ABORT") == -1) {
        if (typeof(error_list[tabId]) == 'undefined' || error_list[tabId] == null) {
            error_list[tab_key] = [];
        }
        //重复的
        for (var i in  error_list[tab_key]) {
            if ( error_list[tab_key][i] == domain_name) {
                return;
            }
        }
        //存在的
        for (var i in block_list) {
            if (block_list[i] == domain_name) {
                return;
            }
        }
        //通用存在的
        for (var i in block_list_system) {
            if (block_list_system[i] == domain_name) {
                return;
            }
        }

        for (var i in  window.complete) {
            if ( window.complete[i] == domain_name) {
                //alert('okd');
                return;
            }
        }
        if (typeof(error_list[tabId]) == 'undefined') {
            error_list[tabId] = [];
        }
        error_list[tabId].push(domain_name);
        localStorage.setItem('5uf_error_list', JSON.stringify(error_list));
        chrome.tabs.query({ currentWindow: true, active: true }, function (tab) {
            if (tabId == tab[0].id) {
                chrome.browserAction.setBadgeText({text:error_list[tabId].length+''});
                chrome.browserAction.setTitle({title:'无忧府VPN '+'当前已探测到'+error_list[tabId].length+'个加载失败的资源'});
            }
        });

        return ;
    }
}, {
    urls: ["<all_urls>"]
});


//关闭标签事件
chrome.tabs.onRemoved.addListener(function (tabId, changeInfo, tab) {
    if (localStorage.getItem('5uf_login_username') == null && localStorage.getItem('5uf_login_password') == null) {
        return;
    }
    //错误列表
    var error_list = localStorage.getItem('5uf_error_list');
    if (typeof(error_list) == 'undefined' || error_list == null) {
        var error_list = [];
        localStorage.setItem('5uf_error_list', JSON.stringify(error_list));
    }
    var error_list = localStorage.getItem('5uf_error_list');
    error_list = JSON.parse(error_list);


    if (typeof(error_list[tabId]) == 'undefined') {
    } else {
        error_list[tabId] = [];
    }
    localStorage.setItem('5uf_error_list', JSON.stringify(error_list));
});

//切换标签事件
chrome.tabs.onActiveChanged.addListener(function (tabId, changeInfo, tab){
    //alert(tabId);
    if (localStorage.getItem('5uf_login_username') == null && localStorage.getItem('5uf_login_password') == null) {
        return;
    }
    //错误列表
    var error_list = localStorage.getItem('5uf_error_list');
    if (typeof(error_list) == 'undefined' || error_list == null) {
        var error_list = [];
        localStorage.setItem('5uf_error_list', JSON.stringify(error_list));
    }
    var error_list = localStorage.getItem('5uf_error_list');
    error_list = JSON.parse(error_list);
    if (typeof(error_list[tabId]) == 'undefined' || error_list[tabId] == null) {
        chrome.browserAction.setBadgeText({text:''});
        chrome.browserAction.setTitle({title:'无忧府VPN '});
    } else {
        if (error_list[tabId].length == 0) {
            chrome.browserAction.setBadgeText({text:''});
            chrome.browserAction.setTitle({title:'无忧府VPN '});
            return;
        }
        var num = error_list[tabId].length;
        chrome.browserAction.setBadgeText({text:num+''});
        chrome.browserAction.setTitle({title:'无忧府VPN '+'当前已探测到'+num+'个加载失败的资源'});
    }


});

chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {

});
*/