/**
 * Created by zhangyu on 14-1-2.
 */

(function () {
    function searchThis(text) {
        //必须top
        top.location.href = 'http://www.baidu.com/s?wd=' + text;
    }

    function getParam(name, search) {
        search = search || window.location.search;
        return decodeURIComponent((search.match(RegExp('[?&]' + name + '=([^&]*)')) || [])[1] || '');
    }

    function getCurrentUrl() {
        return location.href;
    }

    function $(id) {
        return document.getElementById(id);
    }

    var searchReport = function(){
        //window.external.send('data_report','[522,[{"key":2, "value":1}]]')
    }

    var showReport = function(){
        //window.external.send('data_report','[522,[{"key":1, "value":1}]]')
    }

    function init() {

        var currentUrl = getParam('url');

        showReport();

        var handlers = {
            'btnRefresh': function () {
                //todo: qianxun 协议目前还打开不了.
                if(currentUrl.indexOf('qianxun://') == 0){
                    //window.external.send('open_url', '["currenttab", "' + currentUrl + '"]');
                    return;
                }
                //只能用replace
                location.replace(currentUrl);
            },

            'btnSearch': function () {
                searchReport();
                searchThis($('txtSearchBox').value);
            },

            'btnContinue': function () {
                try {
                    //window.external.send('ssl_pass', '["' + currentUrl + '"]');
                } catch (e) {

                }
            },

            'btnClose': function () {
                window.close();
            },

            'btnConnDoctor' : function(){
                //window.external.send('network_diagnose');
            }
        }

        var el;
        for (var id in handlers) {
            el = $(id);
            if (el) {
                el.onclick = handlers[id];
            }
        }


        var txtSearchBox =  $('txtSearchBox'),
            buttonClear = $('button-search-clear');

        if(currentUrl){
            txtSearchBox.value = currentUrl;
            buttonClear.style.display = 'block';
        }else{
            $('btnRefresh').style.display = 'none';
        }

        txtSearchBox.onkeydown = function(e){
            e = e || window.event;
            var keyCode = e.keyCode || e.charCode;
            if(keyCode === 13){
                searchThis(this.value);
            }
        };

        txtSearchBox.onkeyup = function(event) {
            buttonClear.style.display = this.value === '' ? 'none' : 'block';
        };

        buttonClear.onclick = function() {
            txtSearchBox.value = '';
            txtSearchBox.focus();
            this.style.display = 'none';
        };

        setTimeout(function(){txtSearchBox.select()},0);
    }

    init();
}())
