(function(global) {
    var task, img, styleTask, styleImg;

    function createLoading() {
        task = document.createElement('div');
        task.style.cssText = 'position:fixed;background:rgba(0,0,0,0);left:0;top:0;width:100%;height:100%;z-index:9999';
        document.documentElement.appendChild(task);
    };

    function removeLoading() {
        document.documentElement.removeChild(task);
        task = null;
    };

    function JSBridge() {
        this.name = 'JSBridge';
        this.reset = true;
    };

    JSBridge.prototype.device = function() {
        var u = navigator.userAgent;
        var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
        return isAndroid;
    };
    /**
     * @param null
     * JSBridge初始化
     */
    JSBridge.prototype._init = function(callback) {
        if (window.WebViewJavascriptBridge) {
            return callback(WebViewJavascriptBridge);
        }
        if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }
        window.WVJBCallbacks = [callback];
        var WVJBIframe = document.createElement('iframe');
        WVJBIframe.style.display = 'none';
        WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
        document.documentElement.appendChild(WVJBIframe);
        setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
    };
    /**
     * @param null
     * JSBridge 安卓初始化回调接口
     */
    JSBridge.prototype.__init__ = function(bridge) {
        var isAn = this.device();
        if (this.reset && isAn) {
            this.reset = false;
            bridge.init(function(message, responseCallback) {
                console.log('JS got a message', message);
                var data = {
                    'Javascript Responds': '测试中文!'
                };
                console.log('JS responding with', data);
                responseCallback(data);
            });
        }
    };


    /*
     * 调用原生方法
     */
    JSBridge.prototype.callHandler = function(funcName, data, callback) {
        var isAn = this.device();
        var _this = this;
        // _this._init(function (bridge) {
        //     _this.__init__(bridge);
        //     bridge.callHandler(funcName, JSON.stringify(data), function (response) {
        //         if (callback)
        //             callback(JSON.parse(response));
        //     })
        // }.bind(this))
        if(isAn){
            if(window.WebViewJavascriptBridge){
                _this._init(function (bridge) {
                    _this.__init__(bridge);
                    bridge.callHandler(funcName, JSON.stringify(data), function (response) {
                        if (callback)
                            callback(JSON.parse(response));
                    })
                }.bind(this))
            }else{
                document.addEventListener(
                    'WebViewJavascriptBridgeReady'
                    , function() {
                        _this._init(function (bridge) {
                            _this.__init__(bridge);
                            bridge.callHandler(funcName, JSON.stringify(data), function (response) {
                                if (callback)
                                    callback(JSON.parse(response));
                            })
                        }.bind(this))
                    },
                    false
                );
            }
        }else{
            _this._init(function (bridge) {
                _this.__init__(bridge);
                bridge.callHandler(funcName, JSON.stringify(data), function (response) {
                    if (callback)
                        callback(JSON.parse(response));
                })
            }.bind(this))
        }
    };


    /*
     * 注册方法
     */
    JSBridge.prototype.registerHandler = function(funcName,initFuc, params) {
        var isAn = this.device();
        var _this = this;
        //处理android WebViewJavascriptBridge延时问题
        if(isAn) {
            if(window.WebViewJavascriptBridge){
                _this._init(function (bridge) {
                    _this.__init__(bridge);
                    bridge.registerHandler(funcName, function (data, callback) {
                        if (initFuc) {
                            if (data) {
                                initFuc(JSON.parse(data));
                            } else {
                                initFuc();
                            }
                        }
                        /* if(callback)
                         callback(JSON.parse(data))*/
                        if (params) {
                            callback(JSON.stringify(params));
                        } else {
                            callback();
                        }

                    })
                }.bind(this))
            }else{
                document.addEventListener('WebViewJavascriptBridgeReady', function() {
                    _this._init(function (bridge) {
                        _this.__init__(bridge);
                        bridge.registerHandler(funcName, function (data, callback) {
                            if (initFuc) {
                                if (data) {
                                    initFuc(JSON.parse(data));
                                } else {
                                    initFuc();
                                }
                            }
                            /* if(callback)
                             callback(JSON.parse(data))*/
                            if (params) {
                                callback(JSON.stringify(params));
                            } else {
                                callback();
                            }

                        })
                    }.bind(this))
                }, false);
            }
        }else{
            _this._init(function (bridge) {
                _this.__init__(bridge);
                bridge.registerHandler(funcName, function (data, callback) {
                    if (initFuc) {
                        if (data) {
                            initFuc(JSON.parse(data));
                        } else {
                            initFuc();
                        }
                    }
                    /* if(callback)
                     callback(JSON.parse(data))*/
                    if (params) {
                        callback(JSON.stringify(params));
                    } else {
                        callback();
                    }

                })
            }.bind(this))
        }
    };

    /*
     * 获取经纬度
     */
    JSBridge.prototype.getJwd = function(callback, params) {
        this._init(function(bridge) {
            this.__init__(bridge);
            bridge.callHandler( 'getJwd', JSON.stringify({}), function(response) {
                var res = JSON.parse(response);
                jwd = res["longitude"]+","+res["latitude"];
                params["userLocation"] = jwd;
                if(callback)
                    callback(params);
            })
        }.bind(this))
    };
    
    /*
     * 全局变量设置
     */
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = JSBridge;
    } else if (typeof define === 'function' && (define.amd || define.cmd)) {
        define(function() {
            return JSBridge;
        });
    } else {
        global.JSBridge = JSBridge;
    };
})(this);