/// <reference path="../js/jquery.js" />
function doMddBack() {
    //window.history.go(-1);
    console.log("返回");
    if ((navigator.userAgent.indexOf('MSIE') >= 0) &&
    (navigator.userAgent.indexOf('Opera') < 0)) {
        // IE
        if (history.length > 0) {
            window.history.go(-1);
        } else {
            //window.opener = null; window.close();
            doMddCloseClient();
        }
    } else {
        //非IE浏览器
        if (navigator.userAgent.indexOf('Firefox') >= 0 || navigator.userAgent.indexOf('Opera') >= 0 ||
         navigator.userAgent.indexOf('Safari') >= 0 ||
         navigator.userAgent.indexOf('Chrome') >= 0 ||
         navigator.userAgent.indexOf('WebKit') >= 0) {
            if (window.history.length > 1) {
                window.history.go(-1);
            } else {

                //window.opener = null; window.close();
                doMddCloseClient();
            }
        } else {
            //未知的浏览器
            window.history.go(-1);
        }
    }
}
//关闭客户端
function doMddCloseClient() {
    //dir:0发起者，1接受者
    //通讯命令:0开始
    if (checkClient()) {
        var IAMsg = { cmd: "24" };
        var tJSon = JSON.stringify(IAMsg);
        //jsonz字符串
        IAObj.jsSendCmdJsonStr(tJSon);
    } else {
        alert("未定义客户端桥");
    }
}
//关闭并且跳转(全路径)
function doMddReOpenCleint(pFullUrl)
{
        //通讯命令:0开始
    if (checkClient()) {
        var IAMsg = { cmd: "21",userOper:{"UserOperURL":pFullUrl}};
        var tJSon = JSON.stringify(IAMsg);
        //jsonz字符串
        IAObj.jsSendCmdJsonStr(tJSon);
    } else {
        alert("未定义客户端桥");
    }
}
//跳转至原生支付
function doJumpPay() {
    var cmdObj = {};
    if (checkClient()) {
        var IAMsg = { cmd: "26" };
        var tJSon = JSON.stringify(IAMsg);
        //jsonz字符串
        IAObj.jsSendCmdJsonStr(tJSon);
    } else {
        alert("未定义客户端桥");
    }
}
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
//判断是否在客户端
function checkClient() {
    var rClient = false;
    if (typeof (IAObj) != "undefined") {
        rClient = true;
    } else {
        rClient = false;
    }
    return rClient;
}
//判断图片
function getCovertImg(pImgPath)
{
    var rImgPath="";
    if(pImgPath==undefined||pImgPath=="")
    {
        rImgPath="";
    }else{
        var str=new RegExp("http");
        //是否http开头的
        if (str.test(pImgPath)) {
            rImgPath=pImgPath;
        }else if(pImgPath.substr(0,1)=="/"){
            rImgPath=pImgPath;
        }else{
            //漏了http头
            rImgPath="http://"+pImgPath;
        }
    }
    return rImgPath;
}
//获取对当前日期
Date.prototype.format = function (format) {
    var args = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
        "S": this.getMilliseconds()
    };
    if (/(y+)/.test(format))
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var i in args) {
        var n = args[i];
        if (new RegExp("(" + i + ")").test(format))
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? n : ("00" + n).substr(("" + n).length));
    }
    return format;
};
//显示字段
function displayProp(obj) {
    var names = "";
    for (var name in obj) {
        names += name + ": " + obj[name] + ", ";
    }
    return names;
    //alert(names);
}
//是否是字符串
function isString(str) {
    return (typeof str == 'string') && str.constructor == String;
}
//字数限制
function isNotMax(oTextArea){
    return oTextArea.value.length!=oTextArea.getAttribute("maxlength");
}
//字符格式化
/*
举个例子
/两种调用方式
 var template1="我是{0}，今年{1}了";
 var template2="我是{name}，今年{age}了";
 var result1=template1.format("loogn",22);
  var result2=template2.format({name:"loogn",age:22});
*/
String.prototype.format = function(args) {
    var result = this;
    if (arguments.length > 0) {
        if (arguments.length == 1 && typeof (args) == "object") {
            for (var key in args) {
                if(args[key]!=undefined){
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, args[key]);
                }
            }
        }
        else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] != undefined) {
                    var reg = new RegExp("({[" + i + "]})", "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
    }
    return result;
}
//字符格式化2
/*
举个例子
 StringFormat("&Type={0}&Ro={1}&lPlan={2}&Plan={3}&={4}&Id={5}&Id={6}", data1, data2, data3,data4, data5,data6,data7);
*/
function stringFormat() {
         if (arguments.length == 0)
             return null;
         var str = arguments[0];
         for (var i = 1; i < arguments.length; i++) {
             var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
             str = str.replace(re, arguments[i]);
         }
         return str;
}
/*
获取url参数
*/
function expressDicWithURi(pURL)
{
    debugger;
    var rDic=new Object();
   var name,value;
   var str=pURL; //取得整个地址栏
   var num=str.indexOf("?")
   str=str.substr(num+1); //取得所有参数   stringvar.substr(start [, length ]

   var arr=str.split("&"); //各个参数放到数组里
   for(var i=0;i < arr.length;i++){
    num=arr[i].indexOf("=");
    if(num>0){
     name=arr[i].substring(0,num);
     value=arr[i].substr(num+1);
     rDic[name]=value;
     }
    }
    return rDic;
}
//客户端日志
function myClientLog(msg) {
    if (checkClient()) {
        IAObj.jsLog(msg);
    }else{
        console.log(msg);
    }
}
//界面日志
function myUIAlert(msg)
{
     if (checkClient()) {
         IAObj.doTestUi(msg);
        } else {
        alert(msg);
    }
}
//网络请求
function getJWt()
{
    if (checkClient()) {
      return  IAObj.getJwt();
    }else{
        if(jQuery.getUrlParam('mydebug')==1)
        {
            return "Bearer "+jQuery.getUrlParam('Authorization');
        }else{
            return "";
        }
    }
}
//获取用户信息
function getClientUserId()
{
    if (checkClient()) {
        var tUserInfo=IAObj.getUserInfo();
        if(isString(tUserInfo))
        {
            tUserInfo=eval("("+tUserInfo+")");
        }
        return  tUserInfo["userId"];
    }else{
        return jQuery.getUrlParam('uid');
    }
}
//jwt请求
function doServerOperWithJWTBase(pUrl,pType, pData, sucCallBack, compCallBack, errCallBack) {
     var testURL = pUrl;
    var siginURL = testURL;//IAObj.getClientSingnUrl(testURL);
    var tJwt=getJWt();
    // //兼容丢失问题
    // var tAuthorization=jQuery.getUrlParam("Authorization");
    // if(tJwt==""||typeof(tJwt)=="undefined"||tJwt===null)
    // {
    //     if(tAuthorization!=""&& (typeof(tAuthorization)!=undefined))
    //     {
    //         tJwt="Bearer "+tAuthorization;
    //     }
    // }
    // if(tJwt!=undefined&&tJwt!=""&&tJwt!=null&&tAuthorization!=undefined&&tAuthorization!="")
    // {
    //     //缓存
    //     jQuery(".hid_jwt").val(tAuthorization);
    // }
    //alert(tJwt);
    var fromData = pData;
    $.ajax({
        //提交数据的类型 POST GET
        type: pType,
        //提交的网址
        url: siginURL,
        //提交的数据
        data: fromData,
        //返回数据的格式
        datatype: "json",//"xml", "html", "script", "json", "jsonp", "text".
        //添加额外的请求头
        headers : {'Access-Control-Allow-Origin':'*','Authorization':tJwt},
        //在请求之前调用的函数
        beforeSend: function (xmlHttp) {
            console.log("Param:" + JSON.stringify(fromData)+",headers:"+JSON.stringify(this.headers));
        },
        //成功返回之后调用的函数
        success: function (data) {
            console.log("URL:" + siginURL + ",Data:" + JSON.stringify(data));
            sucCallBack(data);

        },
        //调用执行后调用的函数
        complete: function (XMLHttpRequest, textStatus) {
            //alert(XMLHttpRequest.responseText);
            console.log("URL:" + siginURL + ",STATUS:" + textStatus+",XMLHttpRequest:"+JSON.stringify(XMLHttpRequest)+"headers:"+JSON.stringify(this.headers));
            compCallBack(textStatus);
        },
        //调用出错执行的函数
        error: function (error) {
            //myClientLog(tJwt);
            console.log("URL:" + siginURL + ",ERR:" + JSON.stringify(error)+",headers:"+JSON.stringify(this.headers));
            errCallBack(error);

        }
    });
}

//jwt请求
function doServerOperWithJWT_PC(pUrl, pData, sucCallBack, compCallBack, errCallBack) {
    if(jQuery.getUrlParam("mydebug")==1)
    {
      var tOa=jQuery.getUrlParam("Authorization");
      if(tOa!=undefined&&tOa!="")
      {
            pUrl=jQuery.changeURLPar(pUrl,"Authorization",tOa);
      }
    }
    doServerOperWithJWTBase(pUrl,"POST", pData, sucCallBack, compCallBack, errCallBack);
}
//jwt请求
function doServerGetOperWithJWT_PC(pUrl, pData, sucCallBack, compCallBack, errCallBack) {
    if(jQuery.getUrlParam("mydebug")==1)
    {
      var tOa=jQuery.getUrlParam("Authorization");
      if(tOa!=undefined&&tOa!="")
      {
            pUrl=jQuery.changeURLPar(pUrl,"Authorization",tOa);
      }
    }
     doServerOperWithJWTBase(pUrl,"GET", pData, sucCallBack, compCallBack, errCallBack);
}