var config = {
    'search' : '查询',
    'searching' : '查询中',
    'research' : '重新查询',
    'telCheckInfo' : '请输入正确的号码',
    'networkErrorInfo': '网络连接失败,请检查网络后重试',
    'mainPaddingTopInit' : '50px',
    'searchBoxMarginTopInit' : '36px',
    'mainPaddingTopMove' : '34px',
    'searchBoxMarginTopMove' : '0px',
    'linkmain' : 'http://haoma.baidu.com/',  // 百度手机卫士官网
    'linkans' : 'http://haoma.baidu.com/help ' // 常见问题解答
};

var telResultConfig = {
    'reportTitle' : '该号码被<span class="countKey"><span class="count">0</span>人</span>标记为<span class="reportlabelKey">【<span class="reportlabel">金融</span>】</span>号码',
    'reportWarmTips' : '温馨提示: 如果号码信息显示错误，您可进行<a href="###" class="appeal">企业号码申诉/个人号码申诉</a>，审核后，一经确认，立即修正。',
    'commonTelTitle' : '该号码为<span class="locationInfo"></span>号码',
    'commonTelWarnTips' : '温馨提示: 您输入的号码未被收录，若该号码为企业号码，您可进行<a href="###" class="approve">企业号码认证</a>，为企业打造专属的电话名片',
    'telNoExistTitle' :  '无该号码信息',
    'telNoExistWarnTips' : '温馨提示: 您输入的号码未被收录，若该号码为企业号码，您可进行<a href="###" class="approve">企业号码认证</a>，为企业打造专属的电话名片',
    'companyTelTitle' : '该号码为<span class="companyName"></span>号码',
    'companyTelWarnTips' : '温馨提示: 如果号码信息显示错误，您可进行<a href="###" class="appeal">企业号码申诉/个人号码申诉</a>，审核后，一经确认，立即修正。',
};


$(function () {
    var telSearch = window.telSearch || {};
    telSearch = {
        'execOrder' : function (order, key) {
            var info = '';
            try {
                key = (!key ? 'null' : key);
                info = window.external.SyncRequest(order, key);
            } catch (e) {

            }
            return info;
        },
        // 初始化查询面板
        'initSearchView' : function () {
            // 初始化查询一次
            this.initAjax();

            $('.main').css('padding-top',config.mainPaddingTopInit);
            $('.searchBox').css('margin-top', config.searchBoxMarginTopInit);
            var btn = $('.searchButton');
            btn.val(config.search);
            $('.searchButton').css('background','#3682fe');
            $('.searchButton').css('color','#ffffff');
            btn.addClass('search');
            if(btn.hasClass('research')) {
                btn.removeClass('research');
            }
        },
        // 查询成功窗口上移
        'animateSearchview' : function () {
            $('.maintitle').hide();
            $('.main').animate({'padding-top': config.mainPaddingTopMove}, 500);
            $('.searchBox').animate({'margin-top': config.searchBoxMarginTopMove}, 300);
            $('.searchButton').val(config.research);
            $('.searchButton').removeClass('search');
        },

        'clearResult' : function () {
            $('.resultTitle').html('');
            $('.resultWarnTips').html('');
        },

        'checkTelphone' : function (tel) {
            if(!tel) {
                return false;
            }
            // 过滤电话中的格式字符串
            var trimTel = $.trim(tel),
                filterTel = trimTel.replace(/[\s|-]+/g, '');

            // 识别00 开头的海外号码  输入的数字开头是00，13<个数<=30
            if(/^00[0-9]{11,30}$/.test(filterTel)) {    // 海外号码
                return filterTel;
            } else {
                if (/^[0-9]{3,13}$/.test(filterTel)) {   // 校验为数字字符串
                    return filterTel;
                } else {
                    return false;
                }
            }

        },
        'initAjax' : function () {
            $.ajax({
                url: "http://shurufa.baidu.com/shurufa/api/api_get_telephone_data",
                type: "GET",
                data: {
                    telephone: "000"  // 模拟执行一次
                },
                dataType:'jsonp',
                jsonp: 'callback',
                success: function () {
                    //$('#c').html('success');
                },
                error : function () {
                    console.log('error');
                }
            });
        }

    };

    telSearch.initSearchView();

    $('.more').click(function (e) {
        e.stopPropagation();
        if($('.moreul').css('display') == 'none') {
            $('.moreul').show();
        } else {
            $('.moreul').hide();
        }

    });

    $('.telBox *').not('.more').click(function () {
        $('.moreul').hide();
    });

    // 窗口最小化
    $('.win_min').click(function () {
        telSearch.execOrder('minWin');
    });

    // 窗口关闭
    $('.win_close').click(function () {
        telSearch.execOrder('closeWin');
    });

    // 进入官网以及点击上报
    $('.linkmain').parent('li').click(function (e) {
        e.preventDefault();
        var urlParam = { url: config.linkmain};
        telSearch.execOrder('openUrl', JSON.stringify(urlParam));
        telSearch.execOrder('clickReport', 7);
    });

    $('.linkans').parent('li').click(function (e) {
        e.preventDefault();
        var urlParam = { url: config.linkans};
        telSearch.execOrder('openUrl', JSON.stringify(urlParam));
        telSearch.execOrder('clickReport', 8);
    });

    $('.linksjws').click(function (e) {
        e.preventDefault();
        var urlParam = { url: config.linkmain};
        telSearch.execOrder('openUrl', JSON.stringify(urlParam));
        telSearch.execOrder('clickReport', 4);
    });

    $('.searchInput').change(function (e) {
        var str = $(this).val();
        if(str.length >= 30) {
            $(this).val(str.substr(0,30));
            e.preventDefault();
        }
    });

    $('.searchInput').focus(function (e) {
        $('.telCheckTips').html('');
        $('.telCheckTips').hide();
        $('.searchButton').css('background','#3682fe');
        $('.searchButton').css('color','#ffffff');
        $('.searchButton').removeAttr('disabled');
    });

    // 失焦则判断号码校验情况
    $('.searchInput').blur(function () {
        var telephone = $('#searchInput').val();
        if(!telephone || !telSearch.checkTelphone(telephone)){  // 号码校验不通过
            $('.searchButton').css('background','#e2e5e7');
            $('.searchButton').css('color','#7f8a97');
            $('.searchButton').attr('disabled','disabled');
            $('.telCheckTips').html(config.telCheckInfo);
            $('.telCheckTips').show();
        } else {
            if($('.searchButton').hasClass('focus')) {
                $('.searchButton').removeClass('focus');
                // 只处理失去焦点
                return ;
            }
            $('.searchButton').css('background','#3682fe');
            $('.searchButton').css('color','#ffffff');
            telephone = telSearch.checkTelphone(telephone);
            $('#searchInput').val(telephone);
            $('.telCheckTips').html('');
            $('.telCheckTips').hide();
        }
    });

    $('.searchButton').bind('click',function (e) {
        if($('.searchButton').attr('disabled') == 'disabled') {
            return;
        }
        getTelInfo();
    });

    $(document).keypress(function (e) {
        if(!e){
            e = window.event;
        }
        if((e.keyCode||e.which) === 13){
            $('.searchButton').addClass('focus');
            if($('.searchButton').attr('disabled') == 'disabled') {
                return;
            }
            getTelInfo();
            $('.searchInput').blur();
            return false;
        }
    });


    function getTelInfo() {

        if($('.searchButton').hasClass('search')) {
            telSearch.execOrder('clickReport', 1);   // 查询上报
        } else if ($('.searchButton').hasClass('research')) {
            telSearch.execOrder('clickReport', 2);   // 重新查询上报
        }
        var telephone = $('#searchInput').val();


        // 号码校验
        if(!telephone || !telSearch.checkTelphone(telephone)){  // 号码校验不通过
            $('.telCheckTips').html(config.telCheckInfo);
            $('.telCheckTips').show();
            return;
        } else {
            telephone = telSearch.checkTelphone(telephone);
            $('#searchInput').val(telephone);
            $('.telCheckTips').html('');
            $('.telCheckTips').hide();
        }

        // jsonp 调用官网接口
        $.ajax({
            url: "http://shurufa.baidu.com/shurufa/api/api_get_telephone_data",
            type: "GET",
            data: {
                telephone: telephone
            },
            dataType:'jsonp',
            jsonp: 'callback',
            timeout: 8000,
            beforeSend: function () {
                $('.searchButton').val(config.searching);
                $('.searchInput').attr('disabled','disabled');
                $('.searchButton').css('background','#e2e5e7');
                $('.searchButton').css('color','#7f8a97');
            },
            success: function (data) {
                telSearch.clearResult();
                $('.searchButton').val(config.research);
                $('.searchButton').addClass('research');
                $('.searchButton').css('background','#3286fe');
                $('.searchButton').css('color','#ffffff');
                $('.searchButton').removeAttr('disabled');
                $('.searchInput').removeAttr('disabled');
                // 查询成功上报
                telSearch.execOrder('clickReport', 3);
                //console.log(data);

                var response = data['response']['datas'];
                if(response) {
                    var telInfo = response[telephone];
                    if(telInfo['guide'] === false && telInfo['reports']) {
                        $('.resultTitle').html(telResultConfig.reportTitle);
                        $('.resultWarnTips').html(telResultConfig.reportWarmTips);
                        $('.reportlabel').html(telInfo['reports'][0]['name']);   // 被标记名称
                        $('.count').html(telInfo['reports'][0]['count']);        // 被标记次数
                    } else {
                        if(!telInfo['locate'] && telInfo['poi']) {  // 企业号码  优先识别poi
                            $('.resultTitle').html(telResultConfig.companyTelTitle);
                            $('.resultWarnTips').html(telResultConfig.companyTelWarnTips);
                            $('.companyName').html(telInfo['poi']['name']);
                        } else if(telInfo['locate']) {
                            $('.resultTitle').html(telResultConfig.commonTelTitle);
                            $('.resultWarnTips').html(telResultConfig.commonTelWarnTips);
                            $('.locationInfo').html(telInfo['locate']);

                        } else if(telInfo['reports'][0] && telInfo['reports'][0]['count'] == 0) {
                            $('.resultTitle').html(telResultConfig.commonTelTitle);
                            $('.resultWarnTips').html(telResultConfig.commonTelWarnTips);
                            $('.locationInfo').html(telInfo['reports'][0]['name']);
                        }
                    }

                } else {
                    $('.resultTitle').html(telResultConfig.telNoExistTitle);
                    $('.resultWarnTips').html(telResultConfig.telNoExistWarnTips);
                }

                telSearch.animateSearchview();
                $('.searchResult').show();
                if($('.resultTitle').height() > 30) {   // 超过两行显示 调整样式
                    $('.resultTitle').css('text-align','left');
                } else {
                    $('.resultTitle').css('text-align','center');
                }

                // 企业号码认证
                $('.approve').click(function (e) {
                    e.preventDefault();
                    telSearch.execOrder('clickReport', 5);
                    var urlParam = {url: config.linkmain};
                    telSearch.execOrder('openUrl', JSON.stringify(urlParam));
                });

                // 企业号码申诉、个人号码申诉
                $('.appeal').click(function (e) {
                    e.preventDefault();
                    telSearch.execOrder('clickReport', 6);
                    var urlParam = {url: config.linkmain};
                    telSearch.execOrder('openUrl', JSON.stringify(urlParam));
                });

            },
            error: function (xhr) {
                $('.telCheckTips').show();
                $('.telCheckTips').html(config.networkErrorInfo);
                $('.searchButton').css('background','#3682fe');
                $('.searchButton').css('color','#ffffff');
                $('.searchButton').removeAttr('disabled');
                $('.searchInput').removeAttr('disabled');

                if($('.searchButton').hasClass('search')) {
                    $('.searchButton').val(config.search);
                } else if ($('.searchButton').hasClass('research')){
                    $('.searchButton').val(config.research);
                }

            }

        });
    }
});