var TD = {};

TD.ajax = function (pm, succback, errorback) {
    // $.ajax({
    //     type: pm.type || 'GET',
    //     url: pm.url,
    //     dataType: 'json',
    //     data: pm.data || '',
    //     success: function (data) {
    //         if (data.status === 1) {
    //             succback && succback(data.data);
    //         } else {
    //             errorback && errorback(data.message);
    //         }
    //     },
    //     error: function () {
    //         errorback && errorback('网络连接不稳定，请重试或刷新页面！');
    //     }
    // });
    //    ajax({
    //     url: "./TestXHR.aspx",              //请求地址
    //     type: "POST",                       //请求方式
    //     data: { name: "super", age: 20 },        //请求参数
    //     dataType: "json",
    //     success: function (response, xml) {
    //         // 此处放成功后执行的代码
    //     },
    //     fail: function (status) {
    //         // 此处放失败后执行的代码
    //     }
    // });

    function ajax (options) {
        options = options || {};
        options.type = (options.type || 'GET').toUpperCase();
        options.dataType = options.dataType || 'json';
        var params = formatParams(options.data);
        var xhr = null;

        // 创建 - 非IE6 - 第一步
        if (window.XMLHttpRequest) {
            xhr = new XMLHttpRequest();
        } else { // IE6及其以下版本浏览器
            xhr = new ActiveXObject('Microsoft.XMLHTTP');
        }

        // 接收 - 第三步
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                var status = xhr.status;
                if (status >= 200 && status < 300) {
                    options.success && options.success(xhr.responseText, xhr.responseXML);
                } else {
                    options.fail && options.fail(status);
                }
            }
        };

        // 连接 和 发送 - 第二步
        if (options.type === 'GET') {
            xhr.open('GET', options.url + '?' + params, true);
            xhr.send(null);
        } else if (options.type === 'POST') {
            xhr.open('POST', options.url, true);
            // 设置表单提交时的内容类型
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.send(params);
        }
    }
    // 格式化参数
    function formatParams (data) {
        var arr = [];
        for (var name in data) {
            arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
        }
        arr.push(('v=' + Math.random()).replace('.', ''));
        return arr.join('&');
    }

    ajax({
        type: pm.type || 'GET',
        url: pm.url,
        dataType: 'json',
        data: pm.data || '',
        success: function (data) {
            if (data.status === 1) {
                succback && succback(data.data);
            } else {
                errorback && errorback(data.message);
            }
        },
        error: function () {
            errorback && errorback('网络连接不稳定，请重试或刷新页面！');
        }
    });
};

// 网络工具包
TD.util = {};
TD.util.getQuery = function (name) {
    var m = window.location.search.match(new RegExp('(\\?|&)' + name + '=([^&]*)(&|$)'));
    return !m ? '' : decodeURIComponent(m[2]);
};
TD.util.setCookie = function (name, value, expiredays) {
    var exdate = new Date();
    document.cookie = name + '=' + value + ';expires=' +
        ((expiredays === null) ? exdate.setDate(exdate.getDate() + expiredays) : exdate.toGMTString());
};
TD.util.getCookie = function (name) {
    var cStart, cEnd;
    if (document.cookie.length > 0) {
        cStart = document.cookie.indexOf(name + '=');
        if (cStart !== -1) {
            cStart = cStart + name.length + 1;
            cEnd = document.cookie.indexOf(';', cStart);
            if (cEnd === -1) cEnd = document.cookie.length;
            return unescape(document.cookie.substring(cStart, cEnd));
        }
    }
    return '';
};
TD.util.browserType = function () {
    var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串  
    var isOpera = userAgent.indexOf("Opera") > -1; //判断是否Opera浏览器  
    var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera; //判断是否IE浏览器  
    var isEdge = userAgent.indexOf("Windows NT 6.1; Trident/7.0;") > -1 && !isIE; //判断是否IE的Edge浏览器  
    var isFF = userAgent.indexOf("Firefox") > -1; //判断是否Firefox浏览器  
    var isSafari = userAgent.indexOf("Safari") > -1 && userAgent.indexOf("Chrome") == -1; //判断是否Safari浏览器  
    var isChrome = userAgent.indexOf("Chrome") > -1 && userAgent.indexOf("Safari") > -1; //判断Chrome浏览器  

    if (isIE)   
    {  
        var reIE = new RegExp("MSIE (\\d+\\.\\d+);");  
        reIE.test(userAgent);  
        var fIEVersion = parseFloat(RegExp["$1"]);  
        if(fIEVersion == 7)  
        { return "IE7";}  
        else if(fIEVersion == 8)  
        { return "IE8";}  
        else if(fIEVersion == 9)  
        { return "IE9";}  
        else if(fIEVersion == 10)  
        { return "IE10";}  
        else if(fIEVersion == 11)  
        { return "IE11";}  
        else  
        { return "0"}//IE版本过低  
    }
     
    if (isFF) {  return "FF";}  
    if (isOpera) {  return "Opera";}  
    if (isSafari) {  return "Safari";}  
    if (isChrome) { return "Chrome";}  
    if (isEdge) { return "Edge";}  
}

TD.imgPreload = function (callback) {
    // 优先加载loading图片
    var loadingInit = function () {
        var loadingStep = 0;
        var loadingBG = new Image();
        var loadingSprite = new Image();

        loadingBG.src = 'http://airsmart-web.oss-cn-shanghai.aliyuncs.com/upload/images/%E5%85%B1%E9%80%9A/loading_bg.jpg';
        loadingSprite.src = 'http://airsmart-web.oss-cn-shanghai.aliyuncs.com/upload/images/%E5%85%B1%E9%80%9A/loading_sprite2.png';

        loadingBG.onerror = function () {
            console.log('loading error');
            loadingMain();
        }
        loadingSprite.onerror = function () {
            console.log('loading error');
            loadingMain();
        }

        if (!loadingBG.complete) {
            loadingBG.onload = function () {
                loadingStep++;
                if (loadingStep === 2) {
                    loadingMain();
                }
            }
        } else {
            loadingStep++;
        }
        if (!loadingSprite.complete) {
            loadingSprite.onload = function () {
                loadingStep++;
                if (loadingStep === 2) {
                    loadingMain();
                }
            }
        } else {
            loadingStep++;
        }
        loadingBG.complete && loadingSprite.complete && loadingMain();

    }

    //获取所有img标签的url
    var getImgsUrl = function () {
        var imgsArr = [];

        var allImgs = $('img');

        for (var i = 0; i < allImgs.length; i++) {
            imgsArr.push(allImgs[i].src);
        }

        return imgsArr;
    }
    
    var loadingMain = function () {
        // 检查加载进度
        var checkLoad = function () {
            var progress = Math.ceil(count/urls.length*100) + '%';
            if (count >= urls.length) {
                callback && callback();
            }
            console.log(progress);
            console.log(count);
            $('.loading-text').text(progress);
        }

        var count = 0;
        var imgs = [];
        var urls = [];

        urls = getImgsUrl();

        for (var i = 0; i < urls.length; i++) {
            imgs[i] = new Image();
            imgs[i].src = urls[i];

            if (imgs[i].complete) {
                count++;
                checkLoad();
                continue;
            } 
            imgs[i].onload = function () {  
                count++;
                checkLoad();
            }
            imgs[i].onerror = function () {
                console.log('some image load failed');
                count++;
                checkLoad();
            }
        }
    }

    loadingInit();
}
