$(function(){
    chrome.runtime.sendMessage({ action: 'get_storage', data: ['5uf_block_list', '5uf_host_2', '5uf_login_username', '5uf_user_expired', 'crx_version'] }, function (response) {
        var block_list = response['5uf_block_list'];
        block_list = window.safeJsonParse(block_list, []);
        $('#5uf_buy').attr('href', response['5uf_host_2']+'/buy');
        $("#version_show").text(response['crx_version']);
        if (response['5uf_login_username']) {
            $('#svpn_username').html(response['5uf_login_username']);
            var now = Math.round(new Date().getTime()/1000);
    
            var expired = response['5uf_user_expired'];
            if (expired == 0 || expired < now) {
                $('#svpn_days').html('已过期');
            } else {
                var day = (expired - now) / (3600*24);
                $('#svpn_days').html(day.toFixed(2)+'天');
            }
        } else {
            alert('请登录');
            window.close();
            return;
        }
        var init_block_list = function(){
            chrome.runtime.sendMessage({ action: 'get_storage', data: ['5uf_block_list', '5uf_white_list', '5uf_login_username', '5uf_login_password'] }, function (response) {
                var block_list = response['5uf_block_list'];
                var white_list = response['5uf_white_list'];
                block_list = window.safeJsonParse(block_list, []);
                var html = "";
                for (var i in block_list) {
                    html += '<li><button href="" class="btn btn-default" bid="' + i + '" domain="' + block_list[i] + '"><span><i class="glyphicon glyphicon-remove" style="display: none;top:2px;right:3px"></i></span>' + block_list[i] + '</button></li>';
                }
                $("#block_list_container").html(html);

                $("#block_list_container li").hover(function () {
                    $(this).find(".glyphicon").show();
                });
                $("#block_list_container li").mouseleave(function () {
                    $(this).find(".glyphicon").hide();
                });
                white_list = window.safeJsonParse(white_list, []);
                var html = "";
                for (var i in white_list) {
                    html += '<li><button href="" class="btn btn-default" bid="' + i + '" domain="' + white_list[i] + '"><span><i class="glyphicon glyphicon-remove" style="display: none;"></i></span>' + white_list[i] + '</button></li>';
                }
                $("#white_list_container").html(html);

                $("#white_list_container li").hover(function () {
                    $(this).find(".glyphicon").show();
                });
                $("#white_list_container li").mouseleave(function () {
                    $(this).find(".glyphicon").hide();
                });
        
                $("#block_list_container li button").click(function(){
                    var $this = $(this);
                    chrome.runtime.sendMessage({ action: 'get_storage', data: ['5uf_host', '5uf_block_list', '5uf_login_username', '5uf_login_password'] }, function (response) {
                        var block_list = response['5uf_block_list'];
                        
                        block_list = window.safeJsonParse(block_list, []);
                        var bid = $this.attr("bid");
                        if (!confirm("是否要将" + $this.text() + "移出加速名单？")) {
                            return;
                        }
            
                        $.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:$this.attr('domain')},
                            success: function(data){
                                if (data['code']==1) {
                                    var new_block_list = [];
                                    for (var i in block_list) {
                                        if (i==bid) {
                                            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'],
                                    }});
                                    chrome.runtime.sendMessage({ action: 'set_proxy' });
                                    $this.hide(300);
                                } else {
                                    alert(data['msg']);
                                }
                            },
                            error: function () {
                                alert('网络错误，删除失败！');
                            }
                        });
                    });
                });
        
                $("#white_list_container li button").click(function(){
                    var $this = $(this);
                    chrome.runtime.sendMessage({ action: 'get_storage', data: ['5uf_host', '5uf_white_list', '5uf_login_username', '5uf_login_password'] }, function (response) {
                        var white_list = response['5uf_white_list'];
                        
                        white_list = window.safeJsonParse(white_list, []);
                        var bid = $this.attr("bid");
                        if (!confirm("是否要将" + $this.text() + "移出白名单？")) {
                            return;
                        }
            
                        $.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:$this.attr('domain'), type:0},
                            success: function(data){
                                if (data['code']==1) {
                                    var new_white_list = [];
                                    for (var i in white_list) {
                                        if (i==bid) {
                                            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),
                                        "5uf_webproxy_version": data['data']['version'],
                                    }});
                                    chrome.runtime.sendMessage({ action: 'set_proxy' });
                                    $this.hide(300);
                                    //chrome.extension.getBackgroundPage().refresh();
                                } else {
                                    alert(data['msg']);
                                }
                            },
                            error: function () {
                                alert('网络错误，删除失败！');
                            }
                        });
                    });
                });
            });
            
        };
        init_block_list();

        //添加按钮
        var add_domain_handler = function(e){
            chrome.runtime.sendMessage({ action: 'get_storage', data: ['5uf_host', '5uf_block_list', '5uf_login_username', '5uf_login_password'] }, function (response) {
                var block_list = response['5uf_block_list'];
                block_list = window.safeJsonParse(block_list, []);
                var text = $("#add_domain_text");
                if(e.keyCode != undefined && e.keyCode != 13) {
                    return;
                }

                var str = text.val();
                var reg = /^[A-Za-z0-9_]+(\.[A-Za-z0-9_]+)+$/;
                var c = reg.test(str);
                if (!c) {
                    alert('您输入的可能不是域名，请重试！');
                    return;
                }
                var domain = text.val();
                for (var i in block_list) {
                    if (block_list[i] == domain) {
                        alert("域名已存在！");
                        text.val("");
                        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:domain, type:1},
                    success: function(data){
                        if (data['code']==1) {
                            block_list[block_list.length] = domain;
                            $("#block_list_container").html("");
                            chrome.runtime.sendMessage({ action: 'set_storage', data: {
                                "5uf_block_list": JSON.stringify(block_list),
                                "5uf_webproxy_version": data['data']['version']
                            }});
                            init_block_list();
                            $("#add_domain_text").val('');
                        } else {
                            alert(data['msg']);
                        }
                        $("#add_domain_text").focus();
                    },
                    error: function () {
                        alert('网络错误，添加失败！');
                    }
                });
            })
            
        };
        $("#btn_add_domain").click(add_domain_handler);
        $("#add_domain_text").keyup(add_domain_handler);


        //白名单添加按钮
        var add_white_handler = function(e){
            chrome.runtime.sendMessage({ action: 'get_storage', data: ['5uf_host', '5uf_white_list', '5uf_login_username', '5uf_login_password'] }, function (response) {
                var white_list = response['5uf_white_list'];
                white_list = window.safeJsonParse(white_list, []);
                var text = $("#add_white_domain_text");
                if(e.keyCode != undefined && e.keyCode != 13) {
                    return;
                }

                var str = text.val();
                var reg = /^[A-Za-z0-9_]+(\.[A-Za-z0-9_]+)+$/;
                var c = reg.test(str);
                if (!c) {
                    alert('您输入的可能不是域名，请重试！');
                    return;
                }
                var domain = text.val();
                for (var i in block_list) {
                    if (white_list[i] == domain) {
                        alert("域名已存在！");
                        text.val("");
                        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:domain, type:0},
                    success: function(data){
                        if (data['code']==1) {
                            white_list[white_list.length] = domain;
                            $("#white_list_container").html("");
                            chrome.runtime.sendMessage({ action: 'set_storage', data: {
                                "5uf_white_list": JSON.stringify(white_list),
                                "5uf_webproxy_version": data['data']['version']
                            }});
                            init_block_list();
                            $("#add_white_domain_text").val('');
                        } else {
                            alert(data['msg']);
                        }
                        $("#add_white_domain_text").focus();
                    },
                    error: function () {
                        alert('网络错误，添加失败！');
                    }
                });
            });
        };

        $("#btn_add_white_domain").click(add_white_handler);
        $("#add_white_domain_text").keyup(add_white_handler);
    });

    

    $("#btn_white_rules_list").click(function(){
        $(".nav-menu a").removeClass("selected");
        $(this).addClass("selected");
        $("#white_rules_manage").show();
        $("#rules_manage").hide();
        $("#faq_list").hide();
        $("#fresh_list").hide();
    });

    $("#btn_rules_list").click(function(){
        $(".nav-menu a").removeClass("selected");
        $(this).addClass("selected");
        $("#rules_manage").show();
        $("#faq_list").hide();
        $("#fresh_list").hide();
        $("#white_rules_manage").hide();
    });
    $("#btn_faq_list").click(function(){
        $(".nav-menu a").removeClass("selected");
        $(this).addClass("selected");
        $("#rules_manage").hide();
        $("#faq_list").show();
        $("#fresh_list").hide();
        $("#white_rules_manage").hide();
    });
    $("#btn_fresh").click(function(){
        $(".nav-menu a").removeClass("selected");
        $(this).addClass("selected");
        $("#rules_manage").hide();
        $("#faq_list").hide();
        $("#fresh_list").show();
        $("#white_rules_manage").hide();
    });

    var regex = /.*#\/faq$/;
    if (regex.test(location.href))
    {
        $("#btn_faq_list").click();
    }
    

});