//var AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext;
//var _context = new AudioContext();
/*
 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
 * Digest Algorithm, as defined in RFC 1321.
 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for more info.
 */

/*
 * Configurable variables. You may need to tweak these to be compatible with
 * the server-side, but the defaults work in most cases.
 */

var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
var b64pad  = ""; /* base-64 pad character. "=" for strict RFC compliance   */
var chrsz   = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */

/*
 * These are the functions you'll usually want to call
 * They take string arguments and return either hex or base-64 encoded strings
 */
function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));}
function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }

/*
 * Perform a simple self-test to see if the VM is working
 */
function md5_vm_test()
{
  return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}

/*
 * Calculate the MD5 of an array of little-endian words, and a bit length
 */
function core_md5(x, len)
{
  /* append padding */
  x[len >> 5] |= 0x80 << ((len) % 32);
  x[(((len + 64) >>> 9) << 4) + 14] = len;

  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;

    a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
    d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
    c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
    b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
    a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
    d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
    c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
    b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
    a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
    d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
    c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
    b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
    a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
    d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
    c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
    b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);

    a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
    d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
    c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
    b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
    a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
    d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
    c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
    b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
    a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
    d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
    c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
    b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
    a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
    d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
    c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
    b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);

    a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
    d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
    c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
    b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
    a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
    d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
    c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
    b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
    a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
    d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
    c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
    b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
    a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
    d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
    c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
    b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);

    a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
    d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
    c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
    b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
    a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
    d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
    c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
    b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
    a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
    d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
    c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
    b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
    a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
    d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
    c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
    b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
  }
  return Array(a, b, c, d);

}

/*
 * These functions implement the four basic operations the algorithm uses.
 */
function md5_cmn(q, a, b, x, s, t)
{
  return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
  return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
  return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
  return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
  return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}

/*
 * Calculate the HMAC-MD5, of a key and some data
 */
function core_hmac_md5(key, data)
{
  var bkey = str2binl(key);
  if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);

  var ipad = Array(16), opad = Array(16);
  for(var i = 0; i < 16; i++)
  {
    ipad[i] = bkey[i] ^ 0x36363636;
    opad[i] = bkey[i] ^ 0x5C5C5C5C;
  }

  var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
  return core_md5(opad.concat(hash), 512 + 128);
}

/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */
function safe_add(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

/*
 * Bitwise rotate a 32-bit number to the left.
 */
function bit_rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}

/*
 * Convert a string to an array of little-endian words
 * If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
 */
function str2binl(str)
{
  var bin = Array();
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < str.length * chrsz; i += chrsz)
    bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
  return bin;
}

/*
 * Convert an array of little-endian words to a string
 */
function binl2str(bin)
{
  var str = "";
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < bin.length * 32; i += chrsz)
    str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
  return str;
}

/*
 * Convert an array of little-endian words to a hex string.
 */
function binl2hex(binarray)
{
  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i++)
  {
    str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
           hex_tab.charAt((binarray[i>>2] >> ((i%4)*8  )) & 0xF);
  }
  return str;
}

/*
 * Convert an array of little-endian words to a base-64 string
 */
function binl2b64(binarray)
{
  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i += 3)
  {
    var triplet = (((binarray[i   >> 2] >> 8 * ( i   %4)) & 0xFF) << 16)
                | (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
                |  ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
    for(var j = 0; j < 4; j++)
    {
      if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
      else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
    }
  }
  return str;
}

var _context = null;
var _gameSoundsObj = {};
_gameSoundsObj.loadCount = 0;
_gameSoundsObj.completedLoad = 0;
_gameSoundsObj.completed = false;
_gameSoundsObj.soundList = {};
_gameSoundsObj.requestList = {};
_gameSoundsObj.autoBgmList = {};
_gameSoundsObj.loadAudio = function(item,callback){
	var src = "assets/wav/"+item.src;
	if (!_context) callback('Audio Downloader: no web audio context.',null);

	//var request = new XMLHttpRequest();
    //request.open("GET", src, true);
    //request.responseType = "arraybuffer";

    //request.onload = function () {
        //_context["decodeAudioData"](request.response, function(buffer){
            //item.buffer = buffer;
            //_gameSoundsObj.soundList[item.id] = item;
            //_gameSoundsObj.soundList[item.id].touched = false;
            //callback(null, item.src);
        //}, function(){
            //callback('decode error - ' + item.src,null);
        //});
    //};

    //request.onerror = function(){
        //callback('request error - ' + item.src,null);
    //};

    //request.send();
    _gameSoundsObj.requestList[item.src] = new XMLHttpRequest();
    _gameSoundsObj.requestList[item.src].open("GET", src, true);
    _gameSoundsObj.requestList[item.src].responseType = "arraybuffer";

    _gameSoundsObj.requestList[item.src].onload = function () {
        _context["decodeAudioData"](_gameSoundsObj.requestList[item.src].response, function(buffer){
            item.buffer = buffer;
            _gameSoundsObj.completedLoad++;
            //logmessage(_gameSoundsObj.completedLoad+"/"+_gameSoundsObj.loadCount,1);
            _gameSoundsObj.soundList[item.id] = item;
            _gameSoundsObj.soundList[item.id].touched = false;
            //var source = _context.createBufferSource();
			//source.buffer = _gameSoundsObj.soundList[item.id].buffer;//
			//source.connect(_context.destination);//
            callback(null, item.src);
        }, function(){
            callback('decode error - ' + item.src,null);
        });
    };

    _gameSoundsObj.requestList[item.src].onerror = function(){
        callback('request error - ' + item.src,null);
    };

    _gameSoundsObj.requestList[item.src].send();
    if(GameData.OS == ConstVal.OS.apple){
		document.addEventListener('touchstart', function () {
	    	//logmessage("touchstart1",1);
	    	if(!_gameSoundsObj.completed){
	    		//logmessage("touchstart2",1);
		    	var scount = 0;
		    	for(src in _gameSoundsObj.soundList){
		    		scount++;
					//for(var i=0;i<_gameSoundsObj.soundList[src].sourceList.length;i++){
						try{
							if(!_gameSoundsObj.soundList[src].touched){
								//logmessage("touched"+_gameSoundsObj.soundList[src].id,1);
								_gameSoundsObj.soundList[src].touched = true;
								_gameSoundsObj.soundList[src].connected = true;
								var source = _context.createBufferSource();
							    source.buffer = _gameSoundsObj.soundList[src].buffer;//
							    source.connect(_context.destination);//
							}
							
						}catch(e){
	
						}
					//}
				}

				for(src in _gameSoundsObj.autoBgmList){
						try{
							
							//logmessage(src+"touched:"+_gameSoundsObj.soundList[src].touched+"、connected:"+_gameSoundsObj.soundList[src].connected,1);
							if(_gameSoundsObj.soundList[src].touched && _gameSoundsObj.soundList[src].connected){
								//logmessage("autoBgmList:"+_gameSoundsObj.soundList[src].id,1);
								_gameSoundsObj.play(src,true);
								delete _gameSoundsObj.autoBgmList.src;
								break;
							}

						}catch(e){

						}
				}
			
				for(var i=0;i<gameabc_Voice.VoiceFileList.length;i++){
					if(gameabc_Voice.VoiceFileList[i].file){
						scount--;
					}
				}
				if(scount == 0){
					_gameSoundsObj.completed = true;
				}
			}

	    });
	}else{

	}

}
_gameSoundsObj.loadAudios = function(){
	_gameSoundsObj.loadCount = 0;
	_gameSoundsObj.completedLoad = 0;
	for(var i=0;i<gameabc_Voice.VoiceFileList.length;i++){
		if(gameabc_Voice.VoiceFileList[i].file){
			_gameSoundsObj.loadCount ++;
		}
	}
	for(var i=0;i<gameabc_Voice.VoiceFileList.length;i++){
		if(gameabc_Voice.VoiceFileList[i].file){
			var item = {
				id:gameabc_Voice.VoiceFileList[i].file,
				src:gameabc_Voice.VoiceFileList[i].file,
				sourceList:[]
			};
	
			function callback(arg1,arg2){
				if(arg1){
					//logmessage("error",1);
				}else{
					//logmessage("success:"+arg2,1);
				}
			}

			_gameSoundsObj.loadAudio(item,function(arg1,arg2){
				if(arg1){
					//logmessage("error",1);
				}else{
					//logmessage("success:"+arg2,1);
				}
			});
		}
	}
	
	    

}
_gameSoundsObj.play = function(src,loop){
	try{
		//logmessage("_gameSoundsObj.play1"+src+"、"+loop,1);
		var item = _gameSoundsObj.soundList[src];
		if(loop && !item){
			_gameSoundsObj.autoBgmList[src] = src;
			//logmessage("_gameSoundsObj.autoBgmListplay"+src,1);
		}
		if(!item){
			return;
		}
		if(!item.connected){
			return;
		}
		if(loop && item.sourceList.length>0){//背景音 
			return;
		}
		//logmessage("_gameSoundsObj.play2",1);
		var source = _context.createBufferSource();
		
	    source.buffer = item.buffer;//
	    source.connect(_context.destination);//
	    source.loop = loop;
	    source.playing = true;
	    source.isEnded = false;
	    source.onended = function(){
	    	this.isEnded = true;
	    	this.playing = false;
	    	_gameSoundsObj.clearEndedSource();
		}
	    item.sourceList.push(source);
		//logmessage("play",1);
	    source.start(0);//	
	}catch(e){
	}
		
}
_gameSoundsObj.stop = function(src){
	try{
		//logmessage("stop1:"+src,1);
		for(var i=0;i<_gameSoundsObj.soundList[src].sourceList.length;i++){
			//logmessage("stop2:"+src,1);
			if(!_gameSoundsObj.soundList[src].sourceList[i].isEnded){
				
				_gameSoundsObj.soundList[src].sourceList[i].stop();
				_gameSoundsObj.soundList[src].sourceList[i].isEnded = true;
				_gameSoundsObj.soundList[src].sourceList[i].splice(i,1);
				i--;
			}
		
		}
		for(src in _gameSoundsObj.autoBgmList){
			try{
				//logmessage(src+"touched2:"+_gameSoundsObj.soundList[src].touched+"、connected:"+_gameSoundsObj.soundList[src].connected,1);
				if(_gameSoundsObj.soundList[src]){
					//logmessage("autoBgmList2:"+_gameSoundsObj.soundList[src].id,1);
					delete _gameSoundsObj.autoBgmList.src;
				}

			}catch(e){

			}
	}
	}catch(e){

	}
}
_gameSoundsObj.clearAllSource = function(src){
	for(var i=0;i<_gameSoundsObj.soundList[src].sourceList.length;i++){
		try{
			if(!_gameSoundsObj.soundList[src].sourceList[i].isEnded){
				_gameSoundsObj.soundList[src].sourceList[i].stop();
			}
			_gameSoundsObj.soundList[src].sourceList = null;
		}catch(e){

		}
	}
	_gameSoundsObj.soundList[src].sourceList = [];
}
_gameSoundsObj.clearEndedSource = function(){
	for(src in _gameSoundsObj.soundList){
		for(var i=0;i<_gameSoundsObj.soundList[src].sourceList.length;i++){
			try{
				if(_gameSoundsObj.soundList[src].sourceList[i].isEnded){
					_gameSoundsObj.soundList[src].sourceList.splice(i,1);
					i--;
				}

			}catch(e){

			}
		}
	}

}
var dynamicLoading = {
    css: function(path){
		if(!path || path.length === 0){
			throw new Error('argument "path" is required !');
		}
		var head = document.getElementsByTagName('head')[0];
        var link = document.createElement('link');
        link.href = path;
        link.rel = 'stylesheet';
        link.type = 'text/css';
        head.appendChild(link);
    },
    js: function(path){
		if(!path || path.length === 0){
			throw new Error('argument "path" is required !');
		}
		var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.src = path;
        script.type = 'text/javascript';
        head.appendChild(script);
    }
}
var setPostUrl = function setPostUrl(url){
	GameData.sharePostUrl = url;
}
var isArray = function isArray(o){
	return Object.prototype.toString.call(o)=='[object Array]';
}
var gameLog = function gameLog(msg,mode){
	//logmessage(msg,1);
}
var checkMobile = function checkMobile(sMobile){ 
    //var sMobile = document.mobileform.mobile.value
	///^1[3|4|5|7|8|9][0-9]{9}$/ 
    if(!(/^1[3|4|5|6|7|8|9][0-9]{9}$/.test(sMobile))){ 
        return false; 
    } 
    return true;
} 
var sliceStrByKey = function(str,key){
	var idx = str.indexOf(key);
	if(idx>-1){
		return str.slice(0,idx);
	}
	return str;
}
//获取网页参数
var fGetQuery = function(name){//获取参数值
	//var sUrl = window.location.search.substr(1);
	//var r = sUrl.match(new RegExp("(^|&)" + name + "=([^&]*)(&|$)"));
	//return (r == null ? null : unescape(r[2]));
	if(typeof(window.location.search)!="undefined"&&window.location.search!=''){

		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	    var r = window.location.search.substr(1).match(reg);
	    if (r != null) {
	        return r[2];
	    }
    }
        return null;
}
var fGetQuery1 = function(url,name){//获取参数值
	//if(typeof(window.location.search)!="undefined"&&window.location.search!=''){

		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	    var r = url.slice(url.indexOf("?"),url.length).substr(1).match(reg);
	    if (r != null) {
	        return r[2];
	    }
    //}
    return null;
}

var fixUrl = function(url){
	
	var idx = url.indexOf("?");
	if(idx>-1){
		var preUrl = url.substr(0,idx+1);
		var subUrl = url.substr(idx+1,url.length);
		return preUrl+min_replaceAll(subUrl,"\\?","&");
	}else{
		return url;
	}
}
var addParam = function(url,paramKey,paramVal){
    var andStr = "?";
    var beforeparam = url.indexOf("?");
    if(beforeparam != -1){
        andStr = "&";
    }
    return url + andStr + paramKey + "="+ encodeURIComponent(paramVal);
}
var delParam = function(url,paramKey){
    var urlParam = url.substr(url.indexOf("?")+1);
    var beforeUrl = url.substr(0,url.indexOf("?"));
    var nextUrl = "";
     
    var arr = new Array();
    if(urlParam!=""){
        var urlParamArr = urlParam.split("&");
      
        for(var i=0;i<urlParamArr.length;i++){
            var paramArr = urlParamArr[i].split("=");
            if(paramArr[0]!=paramKey){
                arr.push(urlParamArr[i]);
            }
        }
    }
     
    if(arr.length>0){
        nextUrl = "?"+arr.join("&");
    }
    url = beforeUrl+nextUrl;
    return url;
}
var Func=Func||{};
var bForcepc = fGetQuery("dv") == "pc";
//获取当前系统 
var fBrowserRedirect = function(){
//function fBrowserRedirect(){
	var sUserAgent = navigator.userAgent.toLowerCase();
	var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
	var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
	var bIsMidp = sUserAgent.match(/midp/i) == "midp";
	var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
	var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
	var bIsAndroid = sUserAgent.match(/android/i) == "android";
	var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
	var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
	if(bIsIpad||bIsIphoneOs){
		return ConstVal.OS.apple;
	}

	if(bIsAndroid){
		return ConstVal.OS.android;
	}
	if(bIsWM){
		return ConstVal.OS.winphone;
	}
	return ConstVal.OS.other;

}
var getQueryString =function(name) {
	if(typeof(window.location.search)!="undefined"&&window.location.search!=''){

	    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	    var r = window.location.search.substr(1).match(reg);
	    if (r !== null) {
	        return r[2];
	    }
    } 
    return null;
}

var strToJson =function(str){ 
	var json = eval('(' + str + ')'); 
	return json; 
	//return JSON.parse(str);
	
}
//获取字符字节长度 
String.prototype.gblen = function() {    
	var len = 0;    
	for (var i=0; i<this.length; i++) {    
		if (this.charCodeAt(i)>127 || this.charCodeAt(i)==94) {    
			len += 2;    
		} else {    
			len ++;    
		}    
	}    
	return len;    
}

//克隆数组 
Func.cloneArray = function(input_arr){
	return [].concat(input_arr);
}
//精确乘法 
Func.accMul = function(arg1,arg2){
	var m=0,s1=arg1.toString(),s2=arg2.toString();
	try{m+=s1.split(".")[1].length}catch(e){}
	try{m+=s2.split(".")[1].length}catch(e){}
	return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m);
}
//敏感词过滤 
Func.filter = function(str) {
	for (var i = 0; i < arrBan.length; i++) {
		if(str.indexOf(arrBan[i])>=0 && arrBan[i]){
			return true;
		}
	}
	return false;


}
//字符是否为空 
Func.strisNull =function( str ){
	if ( str == "" ) return true;
	var regu = "^[ ]+$";
	var re = new RegExp(regu);
	return re.test(str);
}
Func.setTextArea = function(id,isResize,maxlen){//精灵id，是否禁用大小调整，最大输入长度 
	var obj = null;
	obj = gameabc_face.getdiv("div"+id);
	if(isResize){
		obj.style.resize = "none";
	}
	if(maxlen){
		try{
			maxlen = Number(maxlen);
		}catch(e){
			return ;
		}	
		obj.maxLength = maxlen;	
	}	
	obj = null;

}
Func.setInput = function(id,maxlen){//精灵id，是否禁用大小调整，最大输入长度
	other_setdom("div"+id,"maxlength",maxlen);

}
Func.SetText=function(_msg,len){
	var text_copy="";
	for(var k=0;k<_msg.length;k++){
		text_copy+=_msg[k];
		if(k%len==0&&k!=0){
			text_copy+="\n";
		}
	}
	return text_copy;
}
Func.AjaxHttp = function(_data, func_callbackSucc, func_callbackFail, obj_inputmsg)
{
//
	var obj_config = {};
	obj_config.url = GameData.AjaxUrl;
	obj_config.callbackdata = obj_inputmsg;
	obj_config.data = JSON.stringify(_data);
	obj_config.type = "POST";
	obj_config.success = func_callbackSucc;
	obj_config.error = func_callbackFail;
	min_http(obj_config);
}
Func.AjaxHttp2 = function(_url,_data, func_callbackSucc, func_callbackFail, obj_inputmsg)
{

	var obj_config = {};
	obj_config.url = _url;
	obj_config.callbackdata = obj_inputmsg;
	obj_config.data = JSON.stringify(_data);
	obj_config.type = "POST";
	obj_config.success = func_callbackSucc;
	obj_config.error = func_callbackFail;
	min_http(obj_config);
}
Func.AjaxHttp3 = function(_url,_data, func_callbackSucc, func_callbackFail, obj_inputmsg)
{
	//var sData = "?";
	//for(var key in _data){
		//sData += "&"+key+"="+_data[key];
	//}
	var obj_config = {};
	obj_config.url = _url;
	obj_config.callbackdata = obj_inputmsg;
	obj_config.data = _data;
	obj_config.type = "POST";
	obj_config.success = func_callbackSucc;
	obj_config.error = func_callbackFail;
	min_http(obj_config);
}
var IDValidator = function() {
	var param = {
		error : {
			longNumber : '长数字存在精度问题，请使用字符串传值！ Long number is not allowed, because the precision of the Number In JavaScript.'
		}
	};
	var util = {
		checkArg : function(id) {
			var argType = (typeof id);

			switch (argType) {
			case 'number':
				// long number not allowed
				id = id.toString();
				if (id.length > 15) {
					this.error(param.error.longNumber);
					return false;
				}
				break;
			case 'string':
				break;
			default:
				return false;
			}
			id = id.toUpperCase();
			var code = null;
			if (id.length === 18) {
				// 18位
				code = {
					body : id.slice(0, 17),
					checkBit : id.slice(-1),
					type : 18
				};
			} else if (id.length === 15) {
				// 15位
				code = {
					body : id,
					type : 15
				};
			} else {
				return false;
			}
			return code;
		}
		// 地址码检查
		,
		checkAddr : function(addr, GB2260) {
			var addrInfo = this.getAddrInfo(addr, GB2260);
			return (addrInfo === false ? false : true);
		}
		// 取得地址码信息
		,
		getAddrInfo : function(addr, GB2260) {
			GB2260 = GB2260 || null;
			// 查询GB/T2260,没有引入GB2260时略过
			if (GB2260 === null) {
				return addr;
			}
			if (!GB2260.hasOwnProperty(addr)) {
				// 考虑标准不全的情况，搜索不到时向上搜索
				var tmpAddr;
				tmpAddr = addr.slice(0, 4) + '00';
				if (!GB2260.hasOwnProperty(tmpAddr)) {
					tmpAddr = addr.slice(0, 2) + '0000';
					if (!GB2260.hasOwnProperty(tmpAddr)) {
						return false;
					} else {
						return GB2260[tmpAddr] + '未知地区';
					}
				} else {
					return GB2260[tmpAddr] + '未知地区';
				}
			} else {
				return GB2260[addr];
			}
		}
		// 生日码检查
		,
		checkBirth : function(birth) {
			var year, month, day;
			if (birth.length == 8) {
				year = parseInt(birth.slice(0, 4), 10);
				month = parseInt(birth.slice(4, 6), 10);
				day = parseInt(birth.slice(-2), 10);
			} else if (birth.length == 6) {
				year = parseInt('19' + birth.slice(0, 2), 10);
				month = parseInt(birth.slice(2, 4), 10);
				day = parseInt(birth.slice(-2), 10);
			} else {
				return false;
			}
			// TODO 是否需要判断年份
			/*
			 * if( year<1800 ){ return false; }
			 */
			// TODO 按月份检测
			if (month > 12 || month === 0 || day > 31 || day === 0) {
				return false;
			}

			return true;
		}
		// 顺序码检查
		,
		checkOrder : function(order) {
			// 暂无需检测

			return true;
		}
		// 加权
		,
		weight : function(t) {
			return Math.pow(2, t - 1) % 11;
		}
		// 随机整数
		,
		rand : function(max, min) {
			min = min || 1;
			return Math.round(Math.random() * (max - min)) + min;
		}
		// 数字补位
		,
		str_pad : function(str, len, chr, right) {
			str = str.toString();
			len = len || 2;
			chr = chr || '0';
			right = right || false;
			if (str.length >= len) {
				return str;
			} else {
				for (var i = 0, j = len - str.length; i < j; i++) {
					if (right) {
						str = str + chr;
					} else {
						str = chr + str;
					}
				}
				return str;
			}
		}
		// 抛错
		,
		error : function(msg) {
			var e = new Error();
			e.message = 'IDValidator: ' + msg;
			throw e;
		}
	};
	var _IDValidator = function(GB2260) {
		if (typeof GB2260 !== "undefined") {
			this.GB2260 = GB2260;
		}
		// 建立cache
		this.cache = {};
	};
	_IDValidator.prototype = {
		isValid : function(id) {
			var GB2260 = this.GB2260 || null;
			var code = util.checkArg(id);
			if (code === false) {
				return false;
			}
			// 查询cache
			if (this.cache.hasOwnProperty(id)
					&& typeof this.cache[id].valid !== 'undefined') {
				return this.cache[id].valid;
			} else {
				if (!this.cache.hasOwnProperty(id)) {
					this.cache[id] = {};
				}
			}

			var addr = code.body.slice(0, 6);
			var birth = (code.type === 18 ? code.body.slice(6, 14) : code.body
					.slice(6, 12));
			var order = code.body.slice(-3);

			if (!(util.checkAddr(addr, GB2260) && util.checkBirth(birth) && util
					.checkOrder(order))) {
				this.cache[id].valid = false;
				return false;
			}

			// 15位不含校验码，到此已结束
			if (code.type === 15) {
				this.cache[id].valid = true;
				return true;
			}

			/* 校验位部分 */

			// 位置加权
			var posWeight = [];
			for (var i = 18; i > 1; i--) {
				var wei = util.weight(i);
				posWeight[i] = wei;
			}

			// 累加body部分与位置加权的积
			var bodySum = 0;
			var bodyArr = code.body.split('');
			for (var j = 0; j < bodyArr.length; j++) {
				bodySum += (parseInt(bodyArr[j], 10) * posWeight[18 - j]);
			}

			// 得出校验码
			var checkBit = 12 - (bodySum % 11);
			if (checkBit == 10) {
				checkBit = 'X';
			} else if (checkBit > 10) {
				checkBit = checkBit % 11;
			}
			checkBit = (typeof checkBit === 'number' ? checkBit.toString()
					: checkBit);

			// 检查校验码
			if (checkBit !== code.checkBit) {
				this.cache[id].valid = false;
				return false;
			} else {
				this.cache[id].valid = true;
				return true;
			}

		}

		// 分析详细信息
		,
		getInfo : function(id) {
			var GB2260 = this.GB2260 || null;
			// 号码必须有效
			if (this.isValid(id) === false) {
				return false;
			}
			// TODO 复用此部分
			var code = util.checkArg(id);

			// 查询cache
			// 到此时通过isValid已经有了cache记录
			if (typeof this.cache[id].info !== 'undefined') {
				return this.cache[id].info;
			}

			var addr = code.body.slice(0, 6);
			var birth = (code.type === 18 ? code.body.slice(6, 14) : code.body
					.slice(6, 12));
			var order = code.body.slice(-3);

			var info = {};
			info.addrCode = addr;
			if (GB2260 !== null) {
				info.addr = util.getAddrInfo(addr, GB2260);
			}
			info.birth = (code.type === 18 ? (([ birth.slice(0, 4),
					birth.slice(4, 6), birth.slice(-2) ]).join('-')) : ([
					'19' + birth.slice(0, 2), birth.slice(2, 4),
					birth.slice(-2) ]).join('-'));
			info.sex = (order % 2 === 0 ? 0 : 1);
			info.length = code.type;
			if (code.type === 18) {
				info.checkBit = code.checkBit;
			}

			// 记录cache
			this.cache[id].info = info;

			return info;
		}

		// 仿造一个号
		,
		makeID : function(isFifteen) {
			var GB2260 = this.GB2260 || null;

			// 地址码
			var addr = null;
			if (GB2260 !== null) {
				var loopCnt = 0;
				while (addr === null) {
					// 防止死循环
					if (loopCnt > 10) {
						addr = 110101;
						break;
					}
					var prov = util.str_pad(util.rand(50), 2, '0');
					var city = util.str_pad(util.rand(20), 2, '0');
					var area = util.str_pad(util.rand(20), 2, '0');
					var addrTest = [ prov, city, area ].join('');
					if (GB2260[addrTest]) {
						addr = addrTest;
						break;
					}
				}
			} else {
				addr = 110101;
			}

			// 出生年
			var yr = util.str_pad(util.rand(99, 50), 2, '0');
			var mo = util.str_pad(util.rand(12, 1), 2, '0');
			var da = util.str_pad(util.rand(28, 1), 2, '0');
			if (isFifteen) {
				return addr + yr + mo + da
						+ util.str_pad(util.rand(999, 1), 3, '1');
			}

			yr = '19' + yr;
			var body = addr + yr + mo + da
					+ util.str_pad(util.rand(999, 1), 3, '1');

			// 位置加权
			var posWeight = [];
			for (var i = 18; i > 1; i--) {
				var wei = util.weight(i);
				posWeight[i] = wei;
			}

			// 累加body部分与位置加权的积
			var bodySum = 0;
			var bodyArr = body.split('');
			for (var j = 0; j < bodyArr.length; j++) {
				bodySum += (parseInt(bodyArr[j], 10) * posWeight[18 - j]);
			}

			// 得出校验码
			var checkBit = 12 - (bodySum % 11);
			if (checkBit == 10) {
				checkBit = 'X';
			} else if (checkBit > 10) {
				checkBit = checkBit % 11;
			}
			checkBit = (typeof checkBit === 'number' ? checkBit.toString()
					: checkBit);

			return (body + checkBit);
		}

	};// _IDValidator
	GB2260 = GB2260 == null ? "" : GB2260;
	return new _IDValidator(GB2260);
}
Func.subString=function(str, len, hasDot) 
{ 
	var newLength = 0; 
	var newStr = ""; 
	var chineseRegex = /[^\x00-\xff]/g; 
	var singleChar = ""; 
	var strLength = str.replace(chineseRegex,"**").length; 
	for(var i = 0;i < strLength;i++) 
	{ 
		singleChar = str.charAt(i).toString(); 
		if(singleChar.match(chineseRegex) != null)
		{ 
			newLength += 2; 
		}     
		else 
		{ 
			newLength++; 
		} 
		if(newLength > len) 
		{ 
			break; 
		} 
		newStr += singleChar; 
	} 

	if(hasDot && strLength > len) 
	{ 
		newStr += "..."; 
	} 
	return newStr; 
}
Func.subString2=function(str, len, hasDot)
{
	var newLength = 0;
	var newStr = "";
	var chineseRegex = /[^\x00-\xff]/g;
	var singleChar = "";
	var strLength = str.replace(chineseRegex,"**").length;
	for(var i = 0;i < strLength;i++)
	{
		singleChar = str.charAt(i).toString();
		if(singleChar.match(chineseRegex) != null)
		{
			newLength += 2;
		}
		else
		{
			newLength++;
		}
		if(newLength > len)
		{
			break;
		}
		newStr += singleChar;
	}

	if(hasDot && strLength > len)
	{
		newStr += "...";
	}
	return newStr;
}
Func.getKeywordCount = function(str,keyword){
	var reg = new RegExp(keyword,"g");
	var result = str.match(reg);
	if(result){
		return result.length;
	}
	return 0;
}

//设置普通震动
Func.vibrator=function(time){
	try{
		if(GameData.appstate){
			window.settings.vibrator(time);
		}
	}catch(e){

	}
}
//是否重复震动
Func.repeatvibrator=function(repeat){
	try{
		if(GameData.appstate){
			window.settings.repeatvibrator(repeat);
		}
	}catch(e){

	}
}
//取消震动
Func.canclevibrator=function(){
	try{
		window.settings.canclevibrator();
	}catch(e){

	}
}
//横竖屏 orientation 1 为横屏  2 为竖屏
Func.orientation=function(Orientation){
	try{
		window.settings.orientation(Orientation);
	}catch(e){

	}
}
//通知
Func.notification=function(Ticker,title,content){
	//因为游戏打包之前调用会报错，所以要使用try{}catch{}   try 里面 使用打包调用的函数
	//var Ticker//手机状态栏通知
	//var title//标题
	//var content//内容
	try{
		window.settings.notification(Ticker,title,content);
	}catch(e){

	}
}
Func.sharefinend=function(sharefriend,type,webpageUrl,title,description,spidList){
	GameData.shareFriendInfo = {
		sharefriend:sharefriend,
		type:type,
		webpageUrl:webpageUrl,
		title:title,
		description:description,
		spidList:spidList
	};
	//h5和非h5
	if(GameData.sysConfig.otherShare == 2){
		if(!GameData.h5Version){
			GameUI.openSharePannel();
		}else{
			Func.sharefriend(GameData.shareFriendInfo);
		}
	}else{
		Func.sharefriend(GameData.shareFriendInfo);	
	}
}

Func.visitorLogin = function(){
	//游客身份登入，随机游客数据
	GameData.isVisitor = true;
	GameData.isDeviceLogin = false;
	var WxInfo = Utl.ReadData(Utl.Config.visitorinfo);
	if(WxInfo != null){
		WxInfo = JSON.parse(WxInfo);
		sharelogin(WxInfo.openid,WxInfo.headimgurl,WxInfo.nickname,WxInfo.sex,WxInfo.city,WxInfo.Province,WxInfo.unionid);
	}else{
		var ram = 100000+ifast_random(100000);
		var headLoginList=["http://img5.imgtn.bdimg.com/it/u=110166870,238965605&fm=27&gp=0.jpg",
		"http://www.qqzhi.com/uploadpic/2015-01-15/200511535.jpg",
		"http://img0.imgtn.bdimg.com/it/u=2722294531,1396252661&fm=27&gp=0.jpg",
		"http://p2.gexing.com/touxiang/20130201/1735/510b8c7c1e572_200x200_3.jpg?recache=20131108",
		"http://www.qqzhi.com/uploadpic/2015-01-15/200512924.jpg"];
		sharelogin(""+ram,headLoginList[ifast_random(headLoginList.length)],"游客"+ram,ifast_random(2)+1,"nanchang","jiangxi","ylgame"+ram);
	}

} 
Func.deviceLogin = function(phone,sms){
	//设备登录 
	GameData.isVisitor = false;
	GameData.isDeviceLogin = true;
	var WxInfo = Utl.getCookie(Utl.Config.devicePlayer);
	if(WxInfo){
		WxInfo = JSON.parse(WxInfo);
		sharelogin(WxInfo.openid,WxInfo.headimgurl,WxInfo.nickname,WxInfo.sex,WxInfo.city,WxInfo.Province,WxInfo.unionid,phone,sms);
	}else{
		var unionid = min_randomChar(25);
		if(GameData.phoneInfo){
			if(GameData.phoneInfo.PhoneIMEI){
				unionid = GameData.phoneInfo.PhoneIMEI;
			}else{
				//GameUI.OpenTips("请到设置中打开游戏读取手机信息权限");
				GameData.phoneInfo.PhoneIMEI = unionid;
				Utl.SaveData(Utl.Config.phoneInfo1,JSON.stringify(GameData.phoneInfo));
			}
		}else{
			//GameUI.OpenTips("请到设置中打开游戏读取手机信息权限");
			GameData.phoneInfo = {
				PhoneIMEI:unionid
			};
			Utl.SaveData(Utl.Config.phoneInfo1,JSON.stringify(GameData.phoneInfo));
		}
		var ram = 100000+ifast_random(100000);
		
		var name2 = String(hex_md5(unionid)).slice(0,6);
		var avatar = "";
		if(GameData.sysConfig.avatarUrl){
			var avatar = GameData.sysConfig.avatarUrl + min_random(GameData.sysConfig.avatarRange[0],
			GameData.sysConfig.avatarRange[1])+".jpg";
		}
		var nickName = "User_"+name2;
		sharelogin(unionid,avatar,nickName,ifast_random(2)+1,
		"China","HongKong",unionid,phone,sms);
		//var ram1 = 10000+ifast_random(10000);
		
	}

}
Func.phoneLogin = function(phone,sms){
	//手机登录
	GameData.isVisitor = false;
	GameData.isDeviceLogin = true;
	var WxInfo = Utl.getCookie(Utl.Config.devicePlayer);
	if(WxInfo){
		WxInfo = JSON.parse(WxInfo);
		sharelogin(WxInfo.openid,WxInfo.headimgurl,WxInfo.nickname,WxInfo.sex,WxInfo.city,WxInfo.Province,WxInfo.unionid,phone,sms);
	}else{
		var unionid = "phone_"+phone;
		
		
		var name2 = String(hex_md5(unionid)).slice(0,6);
		var avatar = "";
		if(GameData.sysConfig.avatarUrl){
			var avatar = GameData.sysConfig.avatarUrl + min_random(GameData.sysConfig.avatarRange[0],
			GameData.sysConfig.avatarRange[1])+".jpg";
		}
		var nickName = "User_"+name2;
		sharelogin(unionid,avatar,nickName,ifast_random(2)+1,
		"China","ShangHai",unionid,phone,sms);
		//var ram1 = 10000+ifast_random(10000);
		
	}

}
Func.accreditlogin=function(type){
	//因为游戏打包之前调用会报错，所以要使用try{}catch{}   try 里面 使用打包调用的函数 catch() 里	
	GameData.isVisitor = false;
	GameData.isDeviceLogin = false;
//	logmessage("accreditlogin",1);
	try{
		var tp = 2;
		if(type){
			tp=type;
		}
		window.settings.accreditlogin(tp);
		

	}catch(e){
		if(GameData.h5Version == 1){
			
		}else{
			var headLoginList=[
				"https://img2.baidu.com/it/u=1823726962,2692568839&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500",
				"https://img0.baidu.com/it/u=320875415,2231067789&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500",
				"https://img1.baidu.com/it/u=3407774307,2859661062&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500",
				"https://img2.baidu.com/it/u=1161398577,3592656327&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500",
				"https://img1.baidu.com/it/u=2061657615,4194426181&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=501",
				"https://img2.baidu.com/it/u=3081347414,2363887197&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500",
				"https://img1.baidu.com/it/u=1364384963,3982203144&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500",
				"https://img1.baidu.com/it/u=3041194995,2386060237&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500",
				"https://img2.baidu.com/it/u=2904976445,2884058010&fm=253&fmt=auto&app=120&f=JPEG?w=529&h=500",
				"https://img0.baidu.com/it/u=1801052125,1596537112&fm=253&fmt=auto&app=120&f=JPEG?w=529&h=500",

			];
			var ram = ifast_random(100000);			
			sharelogin("fff23"+ram,headLoginList[ifast_random(headLoginList.length)],"测试"+ram,ifast_random(2)+1,"nanchang","jiangxi","ylgame"+ram);			
			// sharelogin("fff23"+ram,headLoginList[ifast_random(headLoginList.length)],"测试"+ram,ifast_random(2)+1,"nanchang","jiangxi","oLVKis6bj3_l8qspMybG60KV2GN4");
		}
			
	}
}
var sharelogin = function(openid,headimgurl,nickname,sex,city,Province,unionid,phone,sms){
	if(!sex){
		sex = 1;
	}
	
	if(!nickname && !headimgurl){//全为空时无法登陆 
		GameUI.OpenTips("授权失败,请重新授权！");
	}else{
	var wxdata={};
	wxdata.openid = openid;
	wxdata.headimgurl = headimgurl;
	wxdata.nickname = nickname;
	wxdata.sex = sex;
	wxdata.city = city;
	wxdata.Province = Province;
	wxdata.unionid = unionid;
	if(phone){
		wxdata.telphone = phone;
		C_Player.setTel(phone);
	}
	wxdata=JSON.stringify(wxdata);
	// if(GameData.isVisitor){
	// 	Utl.SaveData(Utl.Config.visitorinfo,wxdata);
	// }
	// if(GameData.isDeviceLogin){
	// 	Utl.SaveData(Utl.Config.devicePlayer,wxdata);
	// }
	if(!GameData.isVisitor && !GameData.isDeviceLogin){		
		Utl.setCookie(Utl.Config.wxinfo,wxdata,Utl.Config.maxtime);
	}
	
	C_Player.SetWxInfo(openid,headimgurl,nickname,sex,city,Province,unionid);
	var data={};
	data.agentid = GameData.AgentId;
	data.openid = C_Player.openid;
	data.nickname = C_Player.nickname;
	data.avatar = C_Player.avatar;
	data.sex = C_Player.sex;
	data.province = C_Player.province;
	data.city = C_Player.city;
	data.unionid = C_Player.unionid;
	data.gameid=GameData.GameId;
	data.version = GameData.versionCode;
	data.channelid = GameData.ChannelId;
	data.marketid = GameData.marketID;
	if(phone){
		data.telphone = phone;
	}
	if(sms){
		if(sms != "telphoneAuto"){
			data.smmcode = sms;
			data.telphoneAuto = false;
		}else{
			data.telphoneAuto = true;
		}
	}
	Net.Send_login(data);

	
	} 

}
var sharesuccess = function(success,type){//分享成功回调 

	success = Number(success);
	type = Number(type);
	C_Player.sharesuccess(success,type);
}

Func.getDate = function(){


	var today=new Date();
	var h=today.getHours();
	var m=today.getMinutes();
	if(m<10){
		m="0"+m;
	}
	if(h<10){
		h="0"+h;
	}
	return [h,m];
}
Func.SetDate=function(){
	set_self(154,7,this.getDate()[0],0,0);
	set_self(155,7,this.getDate()[1],0,0);
}
Func.trim =  function(str) {
 return str.replace(/\s+/g, "");
}
Func.insertFlag = function(str,flg,sn,bTemp){
	//this.charCodeAt(i)>127 || this.charCodeAt(i)==94
    var newstr="";
    var strLen = str.length;
    var count = 0;
    var cutIndex = 0;
    if(str.gblen()>sn){
	    for(var i=0;i<str.length;i++){
	    	var delta=0;
	    	if(str.charCodeAt(i)>127 || str.charCodeAt(i)==94){//中文 
				count += 2;
				delta=2;
			
			}else{
				count++;
				delta=1;
			}
			if(count > sn){
				var tmp = str.slice(cutIndex,i);
				if(i==strLen-1){
					if(bTemp){
						newstr += tmp+flg;
					}else{
						newstr += tmp;
					}
				}else{
					newstr += tmp+flg;
					cutIndex=i;
					count = delta;
				}
			}
			if(i==strLen-1 && cutIndex!=i){
				var tmp = str.slice(cutIndex,strLen);
				if(bTemp){
					newstr += tmp+flg;
				}else{
					newstr += tmp;
				}
					
			}
	    	
	
	    }
	}else{
		if(bTemp){
			newstr = str + flg;
		}else{
			newstr = str;
		}
			
	}
    return newstr;
}
Func.countFlag = function(str,flag){
	var rValue=0;
	for(var i=0;i<str.length;i++){
		if(str[i] == flag){
			rValue++;
		}
	}
	return rValue;
}
Func.exit=function(){
	//因为游戏打包之前调用会报错，所以要使用try{}catch{}   try 里面 使用打包调用的函数 catch() 里面使用你自己的函数
	try{
		window.settings.finsh();
		//alert("调用退出程序");
	}catch(e){

		//console.log("程序退出");
	}
}
var phonestate = function(state){//通话状态改变是调用 
	C_Player.phonestate(state);
}
Func.getQueryString=function(name) {
	if(typeof(window.location.search)!="undefined"&&window.location.search!=''){

	var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
	var r = window.location.search.substr(1).match(reg);
	if (r != null) {
		return unescape(r[2]);
	}
	} 
	return null;
}
var appservice = function(service){
	try{
	var isLog = false;
	
	service = Number(service);

	if(GameData.isLogin){ 
		if(service==1){//切回 
			GameData.appstate=true;
			
			if(GameData.heartBeatTimer){
				window.clearTimeout(GameData.heartBeatTimer);
			}
			if(!ConstVal.isGameHall){
				GameData.heartBeatTimer = setTimeout(function(){
					GameUI.OpenTips("网络较慢！",ConstVal.Tips.time);
					GameData.heartBeatStage = true;
	
					//if(Net.ws_tcp.readyState == WebSocket.CLOSED){
	
						//GameData.disType = true;
						//GameData.ConnectType=false;
						//GameData.NetType=1;
						//Logic.TryConnect();
					//}else if(Net.ws_tcp.readyState == WebSocket.OPEN){
	
						//GameData.ConnectType = false;
						//GameData.disType = true;
						//GameData.NetType=1;
						//GameUI.StartLoad();
						//GameData.isClose = true;
						//GameData.isCloseTimer = setTimeout(function(){
							//if(GameData.isClose){
								//Logic.DisConnect();
							//}
						//},5000);
						//Net.ws_tcp.close();
					//}
				},ConstVal.Max.heartbeat);
			}
			//Utl.TurnOnBgm(get_self(4,37,0,0,0));
			if(!ConstVal.isGameHall){
				var exp = new Date();
				if(exp.getTime()-GameData.leaveTime>Game_Config.Max.reconnecttime){//超过重连时间 
					if(Net.ws_tcp.readyState != WebSocket.OPEN){
	
						GameData.disType = true;
						GameData.ConnectType=false;
						GameData.NetType=1;
						Logic.TryConnect();
					}else{
	
						GameData.ConnectType = false;
						GameData.disType = true;
						GameData.NetType=1;
						GameUI.StartLoad();
						GameData.isClose = true;
						//GameData.isCloseTimer = setTimeout(function(){
							//if(GameData.isClose){
								//Logic.DisConnect();
							//}
						//},5000);
						Net.ws_tcp.close();
						GameData.isCloseTimer = setInterval(function(){
							if(GameData.isClose){
								Net.ws_tcp.close();
							}
						},5000);
					}	
				}else{
	
					if(Net.ws_tcp.readyState != WebSocket.OPEN){
	
						GameData.disType = true;
						GameData.ConnectType=false;
						GameData.NetType=1;
						Logic.TryConnect();
					}else{
						if(Desk.inDesk(C_Player.playerid)){
							if(Game_Modify.updateScene){
								Game_Modify.updateScene();
							}
						}else{
							
						}
	
					}
					Utl.playMusic();			
	
				}
			}else{
				Utl.playMusic();
			}
		}else{//切出 
			
			Utl.stopMusic();
			Game_Modify.stopAllSounds();
			GameData.appstate=false;
			for(var i=0;i<ConstVal.InterEffSoundsList.length;i++){
				Utl.stopSound(ConstVal.InterEffSoundsList[i]);
			}
			if(ConstVal.netType == 0){
				var exp = new Date();
				GameData.leaveTime = exp.getTime();
			}else{
				
			}
			//关闭震动 
			Func.canclevibrator();

		}
	}else{

	}
	}catch(e){
			//gameLog("apperror"+e.stack,1);
			//alert(e.stack);
			//if(Game_Config.Debugger.isSubmitError){
				//Net.submit_error(e.stack,"活动测试");
			//}
		}
}
Func.prepareAudio=function(){
	//因为游戏打包之前调用会报错，所以要使用try{}catch{}   try 里面 使用打包调用的函数 catch() 里面使用你自己的函数
	try{
		Utl.stopMusic();	
		GameData.isRecord = true;
		if(isxiaowxgame()){
			GameUI.startRecord();
		}
		window.settings.prepareaudio();
	}catch(e){
		//alert(e);

	}
}
var getaudiourl = function(audiourl,time){//录音成功回调 
//alert("录音成功："+audiourl);
	GameData.isRecord = false;
	Utl.playMusic();
	if(Number(time)>0){
		var data={};
		data.agentid=GameData.AgentId;
		data.gameid=GameData.GameId;
		data.playerid=C_Player.playerid;
		data.roomcode=Desk.roomcode;
		data.voiceurl=audiourl;
		data.time=time;
		if(GameData.chatInfo){
			data.info = GameData.chatInfo;
			data.type=2;
		}
		Net.Send_send_voice(data);
	}
}
Func.mediaTypeAudio=function(audiourl,type,v){
	//因为游戏打包之前调用会报错，所以要使用try{}catch{}   try 里面 使用打包调用的函数 catch() 里面使用你自己的函数
	try{
		window.settings.mediaTypeAudio(audiourl,type,v);
	}catch(e){

		// gameui_play_voice(v);
		Net.submit_error("mediaAudio:audiourl="+audiourl+",type="+type+",user="+v,e.stack);
	}
}
Func.up_imgurl=function(recid,photo){
//[{photo:????,pid:??id}.....];String
//alert(photo);
//?????????????,?????try{}catch{}   try ?? ????????? catch() ??????????
	//return;
	if(!ConstVal.isGameHall){
		try{
			//if(!photo){return;}
			var input_data=[];
			var input_obj={};
			input_obj.photourl=photo;
			input_obj.pid=String(recid);
			input_data.push(input_obj);
	
	
			input_data=JSON.stringify(input_data);
			window.settings.getphoto(input_data);
			//Func.getphoto(input_data);
			var pho=input_obj;
			if(Number(pho.pid)==25){
				up_imgurl(Number(pho.pid),"assets/bmp/00170.png",1);
			//}else if(Number(pho.pid)==115 || Number(pho.pid)==5){
			}else if(exceptSrc.indexOf(Number(pho.pid))>=0){
			}else{
				up_imgurl(Number(pho.pid),"assets/bmp/00170.png",1);
			}
	
		}catch(e){
	
			if(recid==25){
				up_imgurl(recid,"assets/bmp/00170.png",1);
				setTimeout(
				function(){
					if(photo){
						up_imgurl(recid,photo,1);
						GameData.playerHeadImgState = true; 
					}else{
						up_imgurl(recid,"assets/bmp/00170.png",1);
					}
				},ConstVal.Max.headImgTimer);
			}else if(exceptSrc.indexOf(recid)>=0){
				up_imgurl(recid,photo,1);
			}else{
				
				up_imgurl(recid,"assets/bmp/00170.png",1);
				setTimeout(
				function(){
					if(photo){
						up_imgurl(recid,photo,1);
					}else{
						up_imgurl(recid,"assets/bmp/00170.png",1);
					}
				}
				,ConstVal.Max.headImgTimer);
			}	
	
		}
	}else{
		gameHallImport.up_imgurl(recid,photo);
	}
}
var getphoto = function(photo){
	if(!ConstVal.isGameHall){
		var obj = strToJson(photo);
		for(var i=0;i<obj.length;i++){
			var pho=obj[i];	
			if(pho.photourl){
				if(Number(pho.pid)==25){
					if(pho.photourl){
						up_imgurl(Number(pho.pid),pho.photourl,1);
						GameData.playerHeadImgState = true;
					}else{
						up_imgurl(Number(pho.pid),"assets/bmp/00170.png",1);
					}
				}else if(exceptSrc.indexOf(Number(pho.pid))>=0){
					up_imgurl(Number(pho.pid),pho.photourl,1);
				}else{
					//up_imgurl(Number(pho.pid),"assets/bmp/00170.png",1);
					setTimeout(
					function(){
						if(pho.photourl){
							up_imgurl(Number(pho.pid),pho.photourl,1);
						}else{
							up_imgurl(Number(pho.pid),"assets/bmp/00170.png",1);
						}
					}
					,ConstVal.Max.headImgTimer);
				}
			}	
		}
	}else{
		
	}
}

//调用手机默认浏览器打开链接
Func.browser=function(url){
	try{
		if(url){
			url = fixUrl(url);
			var exp = new Date();
			url += "&timestamp=" + exp.getTime();
			window.settings.browser(url);
		}
	}catch(e){
		console.log(url);
	}

}
//主动获取手机电量
Func.getbattery=function(){
	try{
		var battery=window.settings.getbattery();
		return battery;
	}catch(e){
		//alert(e);
		return 1;

	}
}

//手机电量变化调用
var getBattery = function(Battery){
	GameData.Battery=Battery;
	if(GameData.Battery<=0.2){
		set_self(338,43,3,0,0);
	}else{
		set_self(338,43,2,0,0);
	}
}
//分享图片（链接）
Func.sharephotourl=function(sharetype,url){
	try{
		window.settings.sharephotourl(sharetype,url);
	}catch(e){
		//alert(e);
	}
}
//获取网络类型 1 未连接网络  2 连接wifi  3 连接2G/3G/4G
Func.getnetwork=function(){
	try{
		var type = window.settings.getnetwork();
		return type;
	}catch(e){
		return 1;
	}
}

//获取wifi信号ssidname  wifi名称   signalLevel wifi信号强度 0-4 弱到强
Func.getwifisignalLevel=function(){
	try{
		window.settings.getwifisignalLevel();
	}catch(e){
		//alert(e);

	}
}
//WiFi信号变化调用
var getwifiLevel=function(ssidname,signalLevel){
	GameData.WifiLevel=signalLevel;
	GameData.WifiLevel= Number(GameData.WifiLevel);
	switch(GameData.WifiLevel){
		case 0:
		set_self(336,43,1,0,0);
		break;
		case 1:
		case 2:
		set_self(336,43,2,0,0);
		break;
		case 3:
		case 4:
		set_self(336,43,3,0,0);
		break;
	}

}
//网络状况改变 
var getnetwork=function(type){
	type=Number(type);
	switch(type){
		case 1:

		break;
		case 2:
		set_self(336,43,3,0,0);
		Func.getwifisignalLevel();
		break;
		case 3:
		set_self(336,43,4,0,0);
		break;
	}
}
//获取版本类型 
Func.getVersionState = function(){
	//获取版本类型 用于判断版本是否高于服务器版本 
	try{
		//苹果获取结果接口 
		return Number(window.settings.getcompareCode());
	}catch(e){
		return 0;
		//return 1; 
	}
}

Func.startshake = function(){
	if(Utl.ReadData(Utl.Config.shake)==1){
		if(GameData.shakeID != Game_Config.shakeList.nil){
			try{
				window.settings.startshake();
			}catch(e){

			}
		}
	}
}
Func.stopshake = function(){
	try{
		window.settings.stopshake();
	}catch(e){

	}
}
Func.switchshakeVoice = function(Voicetype){
	try{
		window.settings.SwitchShake(Voicetype);
	}catch(e){

	}
}

var shakeEnd = function(){//摇一摇回调 
	Game_Modify.shakeEvent();
}
//获得渠道名称 
Func.getchannelName = function(){//
	try{
		var name=window.settings.getchannelName();
		if(name){
			return name;
		}else{
			return "";	
		}
	}catch(e){
		if(GameData.userAgent != ConstVal.userAgent.uAgent_3){
			return "";
		}else{
			return app_channel;
		}
	}
}

//播放声音 
Func.play_wav = function(src,isloop){
	if(src){
		if(GameData.appstate ||(!GameData.appstate&&isloop==-1)){
			try{
				if(!GameData.isRecord){
					window.settings.srcIsloop(src,isloop);
				}

			}catch(e){
				if(GameData.h5Version == 1 && GameData.OS == ConstVal.OS.apple){
					//logmessage("apple play"+src+"、"+isloop,1);
					switch(isloop){
						case 0:
						case 1:
							_gameSoundsObj.play(src,isloop);
							break;
						case -1:
							_gameSoundsObj.stop(src);
							break;	
					}
				}else{
					if(!GameData.isRecord){
						play_wav(src,isloop);
					}
				}
					
			}			
		}
	}

}

//开启扫一扫
Func.OpenScan = function(){
	try{
		window.settings.opensaoma();
	}catch(e){

	}	
} 
//扫一扫回调数据 
var getsaomaData = function(data){

}
//开启定位
Func.startlocation = function(type){
	try{
		window.settings.startlocation(type);
	}catch(e){

	}
}
//获取定位
Func.getlocation = function(){
	try{
		if(GameData.otherLocation){
			GameData.otherLocationTimes++;
			if(GameData.otherLocationTimes > GameData.otherLocationAllTimes){
				return;
			}
		}
		
		window.settings.getlocationinfo();
	}catch(e){

	}
}
/*
{"address":"江西省南昌市青云谱区施尧路靠近上海浦东发展银行(长天支行)","city":"南昌市",
"cityCode":"0791","country":"中国","district":"青云谱区","latitude":28.623546,"longitude":115.900333,
"province":"江西省","street":"施尧路"}*/
var getlocationinfo=function(locationinfo){
	if(locationinfo){
		try{
			locationinfo = JSON.parse(locationinfo);
			C_Player.SetLocationInfo(locationinfo);
			if(locationinfo.city&&locationinfo.province){
				if(Game_Modify.onLocationInfo){
					Game_Modify.onLocationInfo(locationinfo);
				}
				
				if(GameData.isFirstLogin){
					GameData.isFirstLogin = false;
					var data = {};
						data.agentid = Utl.getAgentID();
						data.playerid = Utl.getMyPlayerid();
						data.info = locationinfo;
						Net.Send_submit_location(data);
					}
				}
			}catch(e){
			}
	}

}
//
Func.SwitchOverGameData = function(webtype,Gamedirectory,gamedownloadurl,data){
	
	try{
		if(ConstVal.isGameHall){
			GameData.hallLogin = false;
			if(!gamedownloadurl || !Gamedirectory){
				gameHallImport.clearGameinfo();
				return;
			}
			Utl.stopMusic();
		}
		window.settings.SwitchOverGameData(webtype,Gamedirectory,gamedownloadurl,data);
	}catch(e){
		console.log("webtype:"+webtype+"Gamedirectory:"+Gamedirectory+"gamedownloadurl:"+gamedownloadurl+"data:"+data);
	}

}
Func.backgameData = function(data){//
	try{
		window.settings.backgameData(data);
	}catch(e){

	}
}
var backgameData = function(){
	var data= {};
	if(C_Player.roomcard>-1){
		data.data = C_Player.returnHallData();
		data.opt = "updatePlayerInfo";
		data.from = 2;
		data.gamename = app_gamename;
		data.gameid = GameData.GameId;
		Func.backgameData(JSON.stringify(data));
	}else{
		data.opt = "saveGameId";
		data.from = 2;
		data.gamename = app_gamename;
		data.gameid = GameData.GameId;
		Func.backgameData(JSON.stringify(data));
	}
	Utl.stopMusic();

}
var getWebdata = function(data){
	//gameLog("收到数据:"+data,1);

	
	//if(data){
		//data = JSON.parse(data);
		//C_Player.setRoomcard(data.roomcard);
	//}
	if(!ConstVal.isGameHall){
		try{
		if(data){
			if(typeof data == "string"){
				data = JSON.parse(data);
			}
			
			if(typeof data.from != "undefined"){
				
				data.from = Number(data.from);
				switch(data.from){
					case 0://游戏间调用 
						switch(data.opt){
							case "uptate_roomcard":
								C_Player.setRoomcard(data.roomcard);	
								break;
							case "loginPlayerid":
								GameData.loginPlayerid = (data.data == GameData.GameId);
								break;
						}
						break;
					case 1://网页调用 
						GameData.ConnectType = false;
						GameData.disType = true;
						GameData.NetType=1;
						GameUI.StartLoad();
						GameData.isClose = true;
						Net.ws_tcp.close();
						//var _msg = data.gamedata;
						GameData.backUrl = data.backurl;
						//if(_msg.route==RouteList.platform||_msg.route==RouteList.agent||_msg.route==RouteList.room){
							//if(min_ExitsFunction(Net[_msg.rpc])){
								//Net[_msg.rpc](_msg);
							//}
						//}else{
							
						//}
						break;
					case 2:
						switch(data.opt){
							case "updateHTML":
								Logic.getHTML();
								break;
						}
						break;
				}
			}
		}
		}catch(e){
			
		}
	}else{
		GameData.hallLogin = true;
		gameHallImport.getWebdata(data);
	}
}
Func.ypayType = function(type){//
	try{
		window.settings.ypayType(type);
	}catch(e){
		console.log("ypayType:"+type);
	}
}
var yPaytype = function(type,num){
	//logmessage("type:"+type+"num:"+num,1);
	type=Number(type);
	num=Number(num);
	switch(type){
		case 1://房卡 
			Net._SendData("youle","agent","update_roomcard",{agentid:GameData.AgentId,playerid:C_Player.playerid,change:num,type:9});
			break;
		case 2://金币 
			Net._SendData("youle","agent","update_bean",{agentid:GameData.AgentId,playerid:C_Player.playerid,change:num,type:9});
			break;
	}
}
Func.getInstallInfo = function(data){//
	try{
		var result = window.settings.getGameinstall(data);
		return Number(result);
	}catch(e){
		return ifast_random(2);
	}
}
/*
{"body":"哈哈哈","price":1,"user":"sdsax11221","type":"ylniuniu001","typeplay":"1"}
?user 用户id???
type：yl+gamename+00N???列子：ylniuniu001?ylniuniu002
?   
tpyealpay 支付类型 1 微信 2 支付宝 
body商品详情  
price 价格
*/
Func.getGamepay = function(data){//
	try{
		window.settings.getGameplay(data);
	}catch(e){
		var dt = JSON.parse(data);
		PayuserPaytypePaystate(dt.playerid,dt.type,1,data.paytype,data)
	}
}
var PayuserPaytypePaystate=function(user,type,state,typeplay,_data){//
	//logmessage("user:"+user+"  type:"+type+"   state:"+state+"  typeplay:"+typeplay,1);
	GameUI.ClosePay();
	GameUI.CloseCheckPay();
	GameUI.EndLoad();
	if(Number(state) == 1){
	_data = JSON.parse(_data);
	var data = {};
	data.agentid = Utl.getAgentID();
	data.playerid = _data.user;
	data.channelid = GameData.ChannelId;
	data.productid = _data.productid;
	data.payid = _data.type;
	data.amount = _data.amount;
	data.money = _data.price;
	data.paytype = _data.typeplay;
	//Net.Send_pay_succ(data);
	var senddata={};
	senddata.app=AppList.app;
	senddata.route=RouteList.agent;
	senddata.rpc=RpcList.pay_succ;
	senddata.data=data;
	Func.AjaxHttp(senddata,pay_succ_s,pay_succ_f);
	var _msg={};
		var rd = Number(C_Player.roomcard) + Number(_data.amount);
		var data1 ={
			roomcard:rd,
			text:"购买"+GameData.roomCardName+",数量:"+_data.amount
		};
		_msg.data=data1; 
		C_Player.UpdateRoomcard(_msg);


	}else{
		GameUI.OpenTips("支付失败！",ConstVal.Tips.time);
	}
}
var pay_succ_s = function(_msg,state,input_msg){
	//console.log("pay_succ_s");
	//_msg = JSON.parse(_msg);
	//var rd = Number(_msg.data.roomcard);
	//var rt = rd + Number(C_Player.roomcard);
	//_msg.data.roomcard = rt;
	//C_Player.UpdateRoomcard(_msg);

}
var pay_succ_f=function(_msg,state,input_msg){
	//console.log("pay_succ_f");
}
Func.callphone = function(tel){
	if(tel){
		window.location.href = 'tel://' + tel;
	}
}
//复制到粘贴板 
Func.gameCopytext = function(text){//
	try{
		window.settings.gameCopytext(text);
	}catch(e){

	}
}
//获得粘贴板内容 
Func.gamepastetext = function(){//
	try{
		return window.settings.gamepastetext();
	}catch(e){
		return "";
	}
}
//获取手机信息 
Func.getphoneInfo = function(){//
	try{
		if(Utl.ReadData(Utl.Config.phoneInfo1)){
			return;
		}
		if(GameData.isGetPhoneInfo){
			return;	
		}else{
			GameData.isGetPhoneInfo = true;	
		}
		return window.settings.getphoneInfo();
	}catch(e){
		var data={};
		data.PhoneIMEI = "phone_"+min_randomChar(25);
		getphoneinfo(data);
	}
}
var getphoneinfo = function(data){
	if(data){
		if(typeof data == "string"){
			data = JSON.parse(data);
			
			//var msg={};
			//msg.info = {};
			//msg.info.phoneInfo = GameData.phoneInfo;
			//msg.info.addrBook = GameData.addressBook;
			//msg.agentid =GameData.AgentId;
			//msg.playerid = C_Player.playerid;
			//Net.Send_submit_phoneinfo(msg);
		}
		Utl.SaveData(Utl.Config.phoneInfo1,JSON.stringify(data));
		GameData.phoneInfo = data;
		GameData.submitPhoneInfo = true;
	}
}

//获取手机信息
Func.getAddressBook = function(){//
	try{
		if(Number(Utl.ReadData(Utl.Config.book)) == 1){
			return;
		}else{
			Utl.SaveData(Utl.Config.book,1);
		}
		return window.settings.getAddressBook();
	}catch(e){
		return "";
	}
}
var getAddressBook = function(data){
	if(data){
		//if(typeof data == "string"){
			//data = JSON.parse(data);
			GameData.addressBook = data;
			var msg={};
			msg.info = {};
			msg.info.phoneInfo = GameData.phoneInfo;
			msg.info.addrBook = GameData.addressBook;
			msg.agentid =GameData.AgentId;
			msg.playerid = C_Player.playerid;
			Net.Send_submit_phoneinfo(msg);
		//}
		GameData.submitAddressBook = true;
	}
}
var gamepastetext_callback = function(resp){
	switch(GameData.gamepastetext){
		case "Logic.pasteRoomCode":
			var reg = /[^0-9]/g;
			var c_text = resp; 
			c_text = c_text.replace(reg,"");
			var _text=String(c_text);
			if(String(c_text).length>6){
				_text=String(c_text).substr(0,6);
			}
			RoomCode = String(_text);
			RoomNum = Number(_text);
			for(var i=0;i<6;i++){
				set_self(236+i,37,0,0,0);
			}
			for(var i=0;i<RoomCode.length;i++){
				set_self(236+i,7,Number(RoomCode[i]),0,0);
				set_self(236+i,37,1,0,0);
			}
			if(RoomCode.length==6){
				var data={};
				data.agentid = GameData.AgentId;
				data.playerid = C_Player.playerid;
				data.gameid = GameData.GameId;
				data.roomcode = RoomNum;
				Net.Send_self_join_room(data);
		
			}
			break;
		case "mouseup_366":
			var text = resp;
			var reg = /[^0-9]/g;
			if(text){
				text = text.replace(reg,"");
				//if(reg.test(text)){
					set_self(365,7,text,0,0);
				//}else{
					//GameUI.OpenTips("粘贴内容格式不符！",ConstVal.Tips.time);
				//}
			}
			break;
		case "mouseup_3217":
			var  text = resp
			var reg = /[^0-9]/g;
			if (text) {
				text = text.replace(reg, "");
				GameData.inputPanelData = text;
				GameUI.setNumberImage(3003, GameData.inputPanelData, 51);
				GameUI.adaptPositionSpid(3003, 3002);
			}
			break;
		case "mouseup_3265":
			var text = resp;
			if(text){
				set_self(551,7,text,0,0);
			}
			break;
	}
}
//获得市场id 
Func.getmarketname = function(){//
	
	try{
		return window.settings.getmarketname();
	}catch(e){
		if(GameData.userAgent != ConstVal.userAgent.uAgent_3){
			return 4;
		}else{
			return app_market;
		}
	}
}
var getmarketname_callback=function(resp){
	switch(GameData.getmarketname){
		case "AppStart":
			GameData.marketID = Number(resp);
			Logic.setGameServer();
			break;
	}
}
//开启关闭语音 
Func.voicePlaying = function(type){//
	try{
		window.settings.voicePlaying(type);
	}catch(e){
		console.log("voicePlaying:"+type);
	}
}
//获得自定义文件夹名 
Func.getOther = function(){//
	try{
		var assetname = window.settings.getOther();
		return assetname;
	}catch(e){
		return "";
	}
}
//获得指定文件夹 
Func.getothername = function(name){//
	//logmessage("old:"+name,1);
	if(GameData.userAgent != ConstVal.userAgent.uAgent_3){
		try{
			var rtname = window.settings.getothername(name);
			return rtname;
		}catch(e){
			return "";
			
		}
	}else{
		return window["app_"+name];
	}
}
//获得指定文件夹回调
var getothername_callback=function(resp){
	switch(resp.type){
		case "agent":	
			if(resp.data){
				GameData.AgentId = resp.data;
			}
			Func.getVersionState();
			break;
		case "gameconfig":
			if(resp.data){
				var url = min_replaceAll(min_replaceAll(resp.data,"-","/",false),"#",":",false);
				//GameData.AjaxUrl = url;
				Game_Config.Debugger.gameserver = "http://"+url+".txt";
			}else{
				//GameData.AjaxUrl = Game_Config.Debugger.gameserver;
			}
			Logic.setAgentId();
			break;
	}
} 
//内部打开网页 Func.OpenurlTitleData(url,title,data)
Func.OpenurlTitleData = function(url,title,data,ort){//
	try{
		if(url){
			url=fixUrl(url);
			var orient=0;
			if(fGetQuery1(url,"orientation")){
				orient = 1;
			}
			var exp = new Date();
			url += "&timestamp=" + exp.getTime();
			window.settings.OpenurlTitleData(url,title,data,orient);
		}
	}catch(e){
		console.log(url);
		console.log(title);
		console.log(data);
	}
}
//退出登录通知app
Func.logoffCallback = function(){
	try{
		window.settings.cancellogin();
	}catch(e){
		console.log("logoff");
	}
	
} 
Func.h5Webpay = function(){
	try{
		var userinfo = {
			openid:C_Player.openid,
			nickname:C_Player.nickname,
			sex:C_Player.sex,
			city:C_Player.city,
			province:C_Player.province,
			headimgurl:C_Player.avatar,
			unionid:C_Player.unionid,
			agentid:GameData.AgentId,
			channelid:GameData.ChannelId,
			playerid:C_Player.playerid,
			return_url:GameData.returnUrl
		};
		window.settings.h5Webpay(JSON.stringify(userinfo));
	}catch(e){
		console.log(JSON.stringify(userinfo));
	}
}
Func.createRoom = function(){
	try{
		var isOpen = 1;
		//if(Game_Modify.getVideoByRoomType){
			//isOpen = Game_Modify.getVideoByRoomType(Desk.roomtype);
		//}
		//if(!GameData.openVideo){return;}
		//if(!GameData.hallConfig.openVideo || !isOpen){return;}
		if(!Desk.videoConfig){
			return;
		}
		var userinfo = {
			agentid:GameData.AgentId,
			roomid:Utl.getRoomcode(),
			gameid:GameData.GameId,
			playerid:C_Player.playerid,
			left:get_self(376,18,0,0,0),
			top:get_self(376,19,0,0,0),
			width:get_self(376,20,0,0,0),
			height:get_self(376,21,0,0,0),
			pmw : 1280,
			pmh : 720
			

		};
		window.settings.createRoom(JSON.stringify(userinfo));
	}catch(e){
		console.log(JSON.stringify(userinfo));
	}
}
Func.exitRoom = function(){
	try{
		var isOpen = 1;
		//if(Game_Modify.getVideoByRoomType){
			//isOpen = Game_Modify.getVideoByRoomType(Desk.roomtype);
		//}
		//if(!GameData.openVideo){return;}
		//if(!GameData.hallConfig.openVideo || !isOpen){return;}
		if(!Desk.videoConfig){
			return;
		}
		var userinfo = {
			agentid:GameData.AgentId,
			roomid:Utl.getRoomcode(),
			gameid:GameData.GameId,
			playerid:C_Player.playerid

		};
		window.settings.exitRoom(JSON.stringify(userinfo));
	}catch(e){
		console.log(JSON.stringify(userinfo));
	}
}
var getVideoinfo=function(_playerid){
	var st = Desk.getPlayerIndexByPlayerid(_playerid);
	if(st<0){
		
	//logmessage("_playeridError!"+_playerid,1);
	return;}
	
	var rValue = {};
	rValue.playerid = _playerid;
	rValue.left = get_self(376+st,18,0,0,0);
	rValue.top = get_self(376+st,19,0,0,0);
	rValue.width = get_self(376+st,20,0,0,0);
	rValue.height = get_self(376+st,21,0,0,0);
	rValue.pmw = 1280;
	rValue.pmh = 720;
	Func.getVideoinfo(JSON.stringify(rValue));
}
Func.getVideoinfo = function(videoinfo){
	try{
		window.settings.getVideoinfo(videoinfo);
	}catch(e){
		
	}
}
var setupWebViewJavascriptBridge=function(callback) {
    if (window.WebViewJavascriptBridge) {
        callback(WebViewJavascriptBridge);
    } else {
        document.addEventListener(
            'WebViewJavascriptBridgeReady'
            , function() {
                callback(WebViewJavascriptBridge);
            },
            false
        );
    }

    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);
}

//在改function 中添加原生调起js方法
Func.registerFunction = function(){
setupWebViewJavascriptBridge(function(bridge) {

    //注册原生调起方法
    //参数1： buttonjs 注册flag 供原生使用，要和原生统一
    //参数2： data  是原生传给js 的数据
    //参数3： responseCallback 是js 的回调，可以通过该方法给原生传数据
    bridge.registerHandler("getVideoinfo",function(data,responseCallback){
		var _playerid = Number(data);
		var st = Desk.getPlayerIndexByPlayerid(_playerid);
		if(st<0){logmessage("_playeridError!"+_playerid,1);return;}
		
		var rValue = {};
		rValue.playerid = _playerid;
		rValue.left = get_self(376+st,18,0,0,0);
		rValue.top = get_self(376+st,19,0,0,0);
		rValue.width = get_self(376+st,20,0,0,0);
		rValue.height = get_self(376+st,21,0,0,0);
		rValue.pmw = 1280;
		rValue.pmh = 720;
		Func.getVideoinfo(JSON.stringify(rValue));
		responseCallback("");
	});
	bridge.registerHandler("sharelogin",function(data,responseCallback){
		//logmessage(data,1);
		if(data){
			if(typeof data == "string"){
				data = strToJson(data);
			}
		}
		
		var openid = data.openid;
		var headimgurl = data.headimgurl;
		var nickname = data.nickname;
		var sex = data.sex;
		var city = data.city;
		var Province = data.Province;
		var unionid = data.unionid;
		if(!sex){
			sex = 1;
		}
		//GameUI.StartLoad();
		if(!nickname && !headimgurl){//全为空时无法登陆
			GameUI.OpenTips("授权失败,请重新授权！");
		}else{
		var wxdata={};
			wxdata.openid = openid;
			wxdata.headimgurl = headimgurl;
			wxdata.nickname = nickname;
			wxdata.sex = sex;
			wxdata.city = city;
			wxdata.Province = Province;
			wxdata.unionid = unionid;

			wxdata=JSON.stringify(wxdata);
			if(GameData.isVisitor){
				Utl.SaveData(Utl.Config.visitorinfo,wxdata);
			}else{
				Utl.setCookie(Utl.Config.wxinfo,wxdata,Utl.Config.maxtime);
			}



			C_Player.SetWxInfo(openid,headimgurl,nickname,sex,city,Province,unionid);
			var data={};
			data.agentid = GameData.AgentId;
			data.openid = C_Player.openid;
			data.nickname = C_Player.nickname;
			data.avatar = C_Player.avatar;
			data.sex = C_Player.sex;
			data.province = C_Player.province;
			data.city = C_Player.city;
			data.unionid = C_Player.unionid;
			data.gameid=GameData.GameId;
			data.version = GameData.versionCode;
			data.channelid = GameData.ChannelId;
			data.marketid = GameData.marketID;
			Net.Send_login(data);
			}
			//responseCallback("");
	});
    
	bridge.registerHandler("gameui_play_voice",function(data,responseCallback){//分享成功回调
		var v = Number(data);
		var bTemp = false;
		if(v >= ConstVal.Com_History.content_tag){
			bTemp = true;
		}
		if(bTemp){
			play_ani(1,ConstVal.Com_History.f_spid+"add"+v,43,1,3,0,600,0,0,0,0,0,0);
		}else{
			var x = Game_Config.Voice.VoiceLoc[v][0];
			var y = Game_Config.Voice.VoiceLoc[v][1];
			var dis_x = Game_Config.Voice.VoiceDis[0];
			var dis_y = Game_Config.Voice.VoiceDis[1];
			var isleft = Game_Config.Voice.isLeft[v];
			var text_len = get_self(642+v,20,0,0,0);
			if(isleft){
				set_self(612+v,18,x,0,0);
				set_self(612+v,19,y,0,0);
				set_self(642+v,18,x+dis_x,0,0);
				set_self(642+v,19,y+dis_y,0,0);
				set_self(612+v,20,text_len+dis_x*2,0,0);
				set_self(612+v,1,83,0,0);
				set_self(612+v,37,1,0,0);
				set_self(642+v,37,1,0,0);
			}else{
				set_self(612+v,18,x-text_len-dis_x*2,0,0);
				set_self(642+v,18,x-text_len-dis_x,0,0);
				set_self(612+v,19,y,0,0);
				set_self(642+v,19,y+dis_y,0,0);
				set_self(612+v,20,text_len+dis_x*2,0,0);
				set_self(612+v,1,86,0,0);
				set_self(612+v,37,1,0,0);
				set_self(642+v,37,1,0,0);

			}
			play_ani(1,642+v,43,1,3,0,Game_Config.Voice.VoiceTime,0,0,0,0,0,0);
		}
		
		//responseCallback("");
	});
	bridge.registerHandler("gameui_stop_voice",function(data,responseCallback){//通话状态改变是调用
		var v=Number(data);
		var bTemp = false;
		if(v>=ConstVal.Com_History.content_tag){
			bTemp = true;
		}
		if(bTemp){
			play_ani(0,ConstVal.Com_History.f_spid+"add"+v,43,1,3,0,600,0,0,0,0,0,0);
			set_self(ConstVal.Com_History.f_spid+"add"+v,43,3,0,0);
		}else{
			set_self(612+v,37,0,0,0);
			set_self(642+v,37,0,0,0);
			play_ani(0,642+v,43);
		}
		//responseCallback("");
	});
	
    bridge.registerHandler("sharesuccess",function(data,responseCallback){//分享成功回调
    	if(data){
			if(typeof data == "string"){
				data = strToJson(data);
			}
		}
		var success = data.success;
		var type = data.type;
		success = Number(success);
		type = Number(type);
		C_Player.sharesuccess(success,type);
		//responseCallback("");
	});
	bridge.registerHandler("getphoneinfo",function(data,responseCallback){//获取手机信息回调 
		if(data){
		if(typeof data == "string"){
			data = strToJson(data);
			
			//var msg={};
			//msg.info = {};
			//msg.info.phoneInfo = GameData.phoneInfo;
			//msg.info.addrBook = GameData.addressBook;
			//msg.agentid =GameData.AgentId;
			//msg.playerid = C_Player.playerid;
			//Net.Send_submit_phoneinfo(msg);
		}
		Utl.SaveData(Utl.Config.phoneInfo1,JSON.stringify(data));
		GameData.phoneInfo = data;
		GameData.submitPhoneInfo = true;
	}  
	});
	
	
	bridge.registerHandler("getAddressBook",function(data,responseCallback){//获取手机信息回调
		if(data){
		//if(typeof data == "string"){
			//data = JSON.parse(data);
			GameData.addressBook = data;
			var msg={};
			msg.info = {};
			msg.info.phoneInfo = GameData.phoneInfo;
			msg.info.addrBook = GameData.addressBook;
			msg.agentid =GameData.AgentId;
			msg.playerid = C_Player.playerid;
			Net.Send_submit_phoneinfo(msg);
		//}
		GameData.submitAddressBook = true;
	}
	});
	bridge.registerHandler("phonestate",function(data,responseCallback){//通话状态改变是调用
		var state = data;
		C_Player.phonestate(state);
		//responseCallback("");
	});
	bridge.registerHandler("appservice",function(data,responseCallback){
		try{
		var service = data;
		var isLog = false;
	
		service = Number(service);
	
		if(GameData.isLogin){
			if(service==1){//切回
				GameData.appstate=true;
				if(GameData.heartBeatTimer){
					window.clearTimeout(GameData.heartBeatTimer);
				}
				if(!ConstVal.isGameHall){
					GameData.heartBeatTimer = setTimeout(function(){
						GameUI.OpenTips("网络较慢！",ConstVal.Tips.time);
						GameData.heartBeatStage = true;
		
						//if(Net.ws_tcp.readyState == WebSocket.CLOSED){
		
							//GameData.disType = true;
							//GameData.ConnectType=false;
							//GameData.NetType=1;
							//Logic.TryConnect();
						//}else if(Net.ws_tcp.readyState == WebSocket.OPEN){
		
							//GameData.ConnectType = false;
							//GameData.disType = true;
							//GameData.NetType=1;
							//GameUI.StartLoad();
							//GameData.isClose = true;
							//GameData.isCloseTimer = setTimeout(function(){
								//if(GameData.isClose){
									//Logic.DisConnect();
								//}
							//},5000);
							//Net.ws_tcp.close();
						//}
					},ConstVal.Max.heartbeat);
				}
				//Utl.TurnOnBgm(get_self(4,37,0,0,0));
				if(ConstVal.netType == 0){
					var exp = new Date();
					if(exp.getTime()-GameData.leaveTime>Game_Config.Max.reconnecttime){//超过重连时间
						if(Net.ws_tcp.readyState != WebSocket.OPEN){
	
							GameData.disType = true;
							GameData.ConnectType=false;
							GameData.NetType=1;
							Logic.TryConnect();
						}else{
	
							GameData.ConnectType = false;
							GameData.disType = true;
							GameData.NetType=1;
							GameUI.StartLoad();
							GameData.isClose = true;
							//GameData.isCloseTimer = setTimeout(function(){
								//if(GameData.isClose){
									//Logic.DisConnect();
								//}
							//},5000);
							Net.ws_tcp.close();
							GameData.isCloseTimer = setInterval(function(){
								if(GameData.isClose){
									Net.ws_tcp.close();
								}
							},5000);
						}
					}else{
	
						if(Net.ws_tcp.readyState != WebSocket.OPEN){
	
							GameData.disType = true;
							GameData.ConnectType=false;
							GameData.NetType=1;
							Logic.TryConnect();
						}else{
							if(Desk.inDesk(C_Player.playerid)){
								Game_Modify.updateScene();
							}
	
						}
						Utl.playMusic();
	
					}
				}else{
	
				}
			}else{//切出
				Utl.stopMusic();
				Game_Modify.stopAllSounds();
				GameData.appstate=false;
				for(var i=0;i<ConstVal.InterEffSoundsList.length;i++){
					Utl.stopSound(ConstVal.InterEffSoundsList[i]);
				}
				if(ConstVal.netType == 0){
					var exp = new Date();
					GameData.leaveTime = exp.getTime();
				}else{
	
				}
				//关闭震动
				Func.canclevibrator();
	
			}
		}else{
	
		}
		//responseCallback("");
		}catch(e){
			//gameLog("apperror"+e.stack,1);
			//alert(e.stack);
			//if(Game_Config.Debugger.isSubmitError){
				//Net.submit_error(e.stack,"活动测试");
			//}
		}
	});
	bridge.registerHandler("getaudiourl",function(data,responseCallback){//录音成功回调
		if(data){
			if(typeof data == "string"){
				data = strToJson(data);
			}
		}
		var audiourl = data.audiourl;
		var time = data.time;
		//alert("录音成功："+audiourl);
		GameData.isRecord = false;
		Utl.playMusic();
		if(Number(time)>0){
			var data={};
			data.agentid=GameData.AgentId;
			data.gameid=GameData.GameId;
			data.playerid=C_Player.playerid;
			data.roomcode=Desk.roomcode;
			data.voiceurl=audiourl;
			data.time=time;
			if(GameData.chatInfo){
							data.info = GameData.chatInfo;
							data.type=2;
						}
			Net.Send_send_voice(data);
		}
		//responseCallback("");
	});
	
	//手机电量变化调用
	bridge.registerHandler("getBattery",function(data,responseCallback){
		//logmessage(data,1);
		
		var Battery = data;
		app_getbattery = Number(Battery);
		GameData.Battery=Number(Battery);
		if(GameData.Battery<=0.2){
			set_self(338,43,3,0,0);
		}else{
			set_self(338,43,2,0,0);
		}
		//responseCallback("");
	});
	//WiFi信号变化调用
	bridge.registerHandler("getwifiLevel",function(data,responseCallback){
		if(data){
			if(typeof data == "string"){
				data = strToJson(data);
			}
		}
		var ssidname = data.ssidname;
		var signalLevel = data.signalLevel;
		GameData.WifiLevel=signalLevel;
		GameData.WifiLevel= Number(GameData.WifiLevel);
		switch(GameData.WifiLevel){
			case 0:
			set_self(336,43,1,0,0);
			break;
			case 1:
			case 2:
			set_self(336,43,2,0,0);
			break;
			case 3:
			case 4:
			set_self(336,43,3,0,0);
			break;
		}
		//responseCallback("");
	});
	//网络状况改变
	bridge.registerHandler("getnetwork",function(data,responseCallback){
		var type=data;
		type = Number(type);
		app_getnetwork = type;
		switch(type){
			case 1:
	
			break;
			case 2:
			set_self(336,43,3,0,0);
			Func.getwifisignalLevel();
			break;
			case 3:
			set_self(336,43,4,0,0);
			break;
		}
		//responseCallback("");
	});
	bridge.registerHandler("shakeEnd",function(data,responseCallback){//摇一摇回调
		Game_Modify.shakeEvent();
		//responseCallback("");
	});
	bridge.registerHandler("yPaytype",function(data,responseCallback){//摇一摇回调
		if(data){
			if(typeof data == "string"){
				data = strToJson(data);
			}
		}
		type=Number(data.type);
		num=Number(data.num);
		switch(type){
			case 1://房卡
				Net._SendData("youle","agent","update_roomcard",{agentid:GameData.AgentId,playerid:C_Player.playerid,change:num,type:9});
				break;
			case 2://金币
				Net._SendData("youle","agent","update_bean",{agentid:GameData.AgentId,playerid:C_Player.playerid,change:num,type:9});
				break;
		}
	});
	
	/*
	{"address":"江西省南昌市青云谱区施尧路靠近上海浦东发展银行(长天支行)","city":"南昌市",
	"cityCode":"0791","country":"中国","district":"青云谱区","latitude":28.623546,"longitude":115.900333,
	"province":"江西省","street":"施尧路"}*/
	bridge.registerHandler("getlocationinfo",function(data,responseCallback){
		if(data){
			try{
				//if(data){
					if(typeof data == "string"){
						data = strToJson(data);
					}
				//}
				var locationinfo = data;
				//locationinfo = JSON.parse(locationinfo);
				C_Player.SetLocationInfo(locationinfo);
				if(locationinfo.city&&locationinfo.province){
					if(Game_Modify.onLocationInfo){
						Game_Modify.onLocationInfo(locationinfo);
					}
					
					if(GameData.isFirstLogin){
						GameData.isFirstLogin = false;
						var data = {};
							data.agentid = Utl.getAgentID();
							data.playerid = Utl.getMyPlayerid();
							data.info = locationinfo;
							Net.Send_submit_location(data);
						}
					}
				}catch(e){
				}
		}
	//responseCallback("");
	});

	bridge.registerHandler("getWebdata",function(data,responseCallback){
		//gameLog("收到数据:"+data,1);
		if(data){
			if(typeof data == "string"){
				data = strToJson(data);
			}
		}
		//if(data){
			//data = JSON.parse(data);
			//C_Player.setRoomcard(data.roomcard);
		//}
		if(!ConstVal.isGameHall){
			if(data){
			
				if(typeof data == "string"){
					data = strToJson(data);
				}
				if(typeof data.from != "undefined"){
				
					data.from = Number(data.from);
					
					switch(data.from){
						case 0://游戏间调用
							switch(data.opt){
								case "uptate_roomcard":
									C_Player.setRoomcard(data.roomcard);
									
									break;
								case "loginPlayerid":
									GameData.loginPlayerid = (data.data == GameData.GameId);
									break;
							}
							break;
						case 1://网页调用
							GameData.ConnectType = false;
							GameData.disType = true;
							GameData.NetType=1;
							GameUI.StartLoad();
							GameData.isClose = true;
							Net.ws_tcp.close();
							
							//var _msg = data.gamedata;
							GameData.backUrl = data.backurl;
							//if(_msg.route==RouteList.platform||_msg.route==RouteList.agent||_msg.route==RouteList.room){
								//if(min_ExitsFunction(Net[_msg.rpc])){
									//Net[_msg.rpc](_msg);
								//}
							//}else{
								
							//}
							break;
						case 2:
						switch(data.opt){
							case "updateHTML":
								Logic.getHTML();
								break;
						}
						break;
					}
				}
			}
		}else{
			GameData.hallLogin = true;
			gameHallImport.getWebdata(data);
		}
	//responseCallback("");
	});
	bridge.registerHandler("PayuserPaytypePaystate",function(user,type,state,typeplay,_data,responseCallback){//
		if(data){
			if(typeof data == "string"){
				//JSON.parse(data);
				data = strToJson(data);
			}
		}
		var user = data.user;
		var type = data.type;
		var state = data.state;
		var typeplay = data.typeplay;
		var _data = data._data;
		//logmessage("user:"+user+"  type:"+type+"   state:"+state+"  typeplay:"+typeplay,1);
		GameUI.ClosePay();
		GameUI.CloseCheckPay();
		GameUI.EndLoad();
		if(Number(state) == 1){
		//_data = JSON.parse(_data);
		var data = {};
		data.agentid = Utl.getAgentID();
		data.playerid = _data.user;
		data.channelid = GameData.ChannelId;
		data.productid = _data.productid;
		data.payid = _data.type;
		data.amount = _data.amount;
		data.money = _data.price;
		data.paytype = _data.typeplay;
		//Net.Send_pay_succ(data);
		var senddata={};
		senddata.app=AppList.app;
		senddata.route=RouteList.agent;
		senddata.rpc=RpcList.pay_succ;
		senddata.data=data;
		Func.AjaxHttp(senddata,pay_succ_s,pay_succ_f);
		var _msg={};
			var rd = Number(C_Player.roomcard) + Number(_data.amount);
			var data1 ={
				roomcard:rd,
				text:"购买"+GameData.roomCardName+",数量:"+_data.amount
			};
			_msg.data=data1;
			C_Player.UpdateRoomcard(_msg);
	
	
		}else{
			GameUI.OpenTips("支付失败！",ConstVal.Tips.time);
		}
		//responseCallback("");
	});
    bridge.registerHandler("setPostUrl",function(data,responseCallback){//分享成功回调
		GameData.sharePostUrl = data;
  	
	});
	bridge.registerHandler("getphoto",function(data,responseCallback){//下载完成回调
		if(!ConstVal.isGameHall){
		var obj = strToJson(data);
		for(var i=0;i<obj.length;i++){
			var pho=obj[i];
			if(pho.photourl){
				if(Number(pho.pid)==25){
					if(pho.photourl){
						up_imgurl(Number(pho.pid),pho.photourl,1);
						GameData.playerHeadImgState = true;
					}else{
						up_imgurl(Number(pho.pid),"assets/bmp/00170.png",1);
					}
				}else if(exceptSrc.indexOf(Number(pho.pid))>=0){
					up_imgurl(Number(pho.pid),pho.photourl,1);
				}else{
					//up_imgurl(Number(pho.pid),"assets/bmp/00170.png",1);
					setTimeout(
					function(){
						if(pho.photourl){
							up_imgurl(Number(pho.pid),pho.photourl,1);
						}else{
							up_imgurl(Number(pho.pid),"assets/bmp/00170.png",1);
						}
					}
					,ConstVal.Max.headImgTimer);
				}
			}
		}
	}else{

	}
  
	});

    bridge.registerHandler("getcameraaAddress",function(data,responseCallback){// data  相片地址


	});

    //参数1： pay 注册flag 供原生使用，要和原生统一
    //参数2： 是调起原生时向原生传递的参数
    //参数3： 原生调用回调返回的数据
	//Func.getVersionState = function(){   
		//var returnData = 0;
		//bridge.callHandler('getcompareCode','',function(resp){
				//returnData = resp;
	        //}
	     //);
		 //return returnData;
	//}
	Func.getphoto = function(data){
		bridge.callHandler('getphoto',data,function(resp){
		
			}
		);
	}
	Func.h5Webpay=function(){
		//?????????????,?????try{}catch{}   try ?? ?????????
		//var Ticker//???????
		//var title//??
		//var content//??
		try{
			//window.settings.notification(Ticker,title,content);
			var data = {
				openid:C_Player.openid,
				nickname:C_Player.nickname,
				sex:C_Player.sex,
				city:C_Player.city,
				province:C_Player.province,
				headimgurl:C_Player.avatar,
				unionid:C_Player.unionid,
				agentid:GameData.AgentId,
				channelid:GameData.ChannelId,
				playerid:C_Player.playerid,
				return_url:GameData.returnUrl
			};
			bridge.callHandler('h5Webpay',data,function(resp){

		        }
		     );
		}catch(e){
	
		}
	}

	Func.up_imgurl=function(recid,photo){
		//因为游戏打包之前调用会报错，所以要使用try{}catch{}   try 里面 使用打包调用的函数 catch() 里面使用你自己的函数
		try{
			if(!ConstVal.isGameHall){
				if(GameData.OS == ConstVal.OS.android){
					var input_data=[];
					var input_obj={};
					input_obj.photourl=photo;
					input_obj.pid=String(recid);
					input_data.push(input_obj);
			
			
					input_data=JSON.stringify(input_data);
					//bridge.callHandler('getphoto',input_data,function(resp){

				       //}
				    //);
				    Func.getphoto(input_data);
				    var pho=input_obj;
					if(Number(pho.pid)==25){
						up_imgurl(Number(pho.pid),"assets/bmp/00170.png",1);
					//}else if(Number(pho.pid)==115 || Number(pho.pid)==5){
					}else if(exceptSrc.indexOf(Number(pho.pid))>=0){
					}else{
						up_imgurl(Number(pho.pid),"assets/bmp/00170.png",1);
					}
				}else{
					if(recid==25){
						up_imgurl(recid,"assets/bmp/00170.png",1);
						setTimeout(
						function(){
							if(photo){
								up_imgurl(recid,photo,1);
								GameData.playerHeadImgState = true; 
							}else{
								up_imgurl(recid,"assets/bmp/00170.png",1);
							}
						},ConstVal.Max.headImgTimer);
					}else if(exceptSrc.indexOf(recid)>=0){
						up_imgurl(recid,photo,1);
					}else{
						
						up_imgurl(recid,"assets/bmp/00170.png",1);
						setTimeout(
						function(){
							if(photo){
								up_imgurl(recid,photo,1);
							}else{
								up_imgurl(recid,"assets/bmp/00170.png",1);
							}
						}
						,ConstVal.Max.headImgTimer);
					}
				}
			
			}else{
						gameHallImport.up_imgurl(recid,photo);
					}

		}catch(e){
			
		}
	}
	Func.getVideoinfo = function(data){
		try{
			
			data = JSON.parse(data);
			bridge.callHandler('getVideoinfo',data,function(resp){

				}
			 );
		}catch(e){
			
		}
	}
	Func.getphoneInfo = function(){
		try{
			if(Utl.ReadData(Utl.Config.phoneInfo1)){
				return;
			}
			if(GameData.isGetPhoneInfo){
				return;
			}else{
				GameData.isGetPhoneInfo = true;
			}
			bridge.callHandler('getphoneInfo',"",function(resp){
				
				}
			 );
		}catch(e){

		}
	
	}
	Func.getAddressBook = function(){
		try{
			if(Number(Utl.ReadData(Utl.Config.book)) == 1){
				return;
			}else{
				Utl.SaveData(Utl.Config.book,1);
			}
			bridge.callHandler('getAddressBook',"",function(resp){

				}
			 );
		}catch(e){

		}

	}
	Func.createRoom=function(){
		try{
			var isOpen = 1;
			//if(Game_Modify.getVideoByRoomType){
				//isOpen = Game_Modify.getVideoByRoomType(Desk.roomtype);
			//}
			//if(!GameData.openVideo){return;}
			if(!GameData.hallConfig.openVideo || !isOpen){return;}
			if(!Desk.videoConfig){
				return;
			}
			var userinfo = {
				agentid:GameData.AgentId,
				roomid:Utl.getRoomcode(),
				gameid:GameData.GameId,
				playerid:C_Player.playerid,
				left:get_self(376,18,0,0,0),
				top:get_self(376,19,0,0,0),
				width:get_self(376,20,0,0,0),
				height:get_self(376,21,0,0,0),
				pmw : 1280,
				pmh : 720

			};
			bridge.callHandler('createRoom',userinfo,function(resp){

		        }
		     );
		}catch(e){
	
		}
	}
	Func.exitRoom=function(){
		try{
			var isOpen = 1;
			//if(Game_Modify.getVideoByRoomType){
				//isOpen = Game_Modify.getVideoByRoomType(Desk.roomtype);
			//}
			//if(!GameData.openVideo){return;}
			if(!GameData.hallConfig.openVideo || !isOpen){return;}
			if(!Desk.videoConfig){
				return;
			}
			var userinfo = {
				agentid:GameData.AgentId,
				gameid:GameData.GameId,
				roomid:Utl.getRoomcode(),
				playerid:C_Player.playerid

			};
			bridge.callHandler('exitRoom',userinfo,function(resp){

		        }
		     );
		}catch(e){
	
		}
	}
	Func.accreditlogin=function(data){
	//因为游戏打包之前调用会报错，所以要使用try{}catch{}   try 里面 使用打包调用的函数 catch() 里面使用你自己的函数
		GameData.isVisitor = false;
		try{
			var tp = 2;
			if(data){
				tp=data;
			}
			// window.settings.accreditlogin();
			bridge.callHandler('accreditlogin',data,function(resp){
				
				}
			);

		}catch(e){
			var headLoginList=[	"http://pic.fxxz.com/up/2016-6/2016060511335263357.png",
			"http://pic.fxxz.com/up/2016-6/2016060511335249995.png",
			"http://pic.fxxz.com/up/2016-6/2016060511335146994.png",
			"http://pic.fxxz.com/up/2016-6/2016060511335682256.png",
			"http://pic.fxxz.com/up/2016-6/2016060511335333433.png"];
			var ram = ifast_random(100000);
			 //sharelogin("fff23"+ram,headLoginList[ifast_random(5)],"测试"+ram,ifast_random(1)+1,"nanchang","jiangxi",222);
			sharelogin("fff23"+ram,headLoginList[ifast_random(5)],"测试测试测试"+ram,ifast_random(1)+1,"nanchang","jiangxi","ylgame"+ram);
		}
	}
	//退出登录通知app
	Func.logoffCallback = function(){
		try{
			//window.settings.cancellogin();
			bridge.callHandler('cancellogin','',function(resp){

				}
			 );
		}catch(e){
			console.log("logoff");
		}
	
	}
	//内部打开网页
	Func.OpenurlTitleData = function(url,title,data,ort){//
		try{
			if(url){
				url=fixUrl(url);
				var orient=0;
				if(fGetQuery1(url,"orientation")){
					orient = 1;
				}
				var exp = new Date();
				url += "&timestamp=" + exp.getTime();
				var data={
					url:url,
					title:title,
					data:data,
					orientation:orient
				};
				//window.settings.OpenurlTitleData(url,title,data);
				bridge.callHandler('OpenurlTitleData',data,function(resp){
	
					}
				);
			}
		}catch(e){
			console.log(url+"、"+title+"、"+data);
		}
	}
	//获得指定文件夹
	//Func.getothername = function(name){//
		//var rtname = "";
		//try{
			//var rtname = window.settings.getothername(name);
			//return rtname;
			//bridge.callHandler('getothername',"",getothername_callback
			//);
			
		//}catch(e){
			
		//}
		//return rtname;
		//var aaa = window["app_"+name];
		//logmessage("name:"+name,1);		
		//return window["app_"+name];
	//}
	//获得自定义文件夹名
	Func.getOther = function(){//
		var assetname = "";
		try{
			//var assetname = window.settings.getOther();
			//return assetname;
			bridge.callHandler('getOther',"",function(resp){
					assetname = resp;
				}
			);
		}catch(e){
			
		}
		return assetname;
	}
	//开启关闭语音
	Func.voicePlaying = function(type){//
		try{
			//window.settings.voicePlaying(type);
			bridge.callHandler('voicePlaying',type,function(resp){
					
				}
			);
		}catch(e){
			console.log("voicePlaying:"+type);
		}
	}
	//复制到粘贴板
	Func.gameCopytext = function(text){//
		try{
			//window.settings.gameCopytext(text);
			bridge.callHandler('gameCopytext',text,function(resp){

				}
			);
		}catch(e){
	
		}
	}
	//打开拍照
	Func.opencamera = function(){
		bridge.callHandler('opencamera',"",function(resp){
		
		   }
		);
	}
	//获得粘贴板内容
	Func.gamepastetext = function(){//
		var returnValue = "";
		try{
			//return window.settings.gamepastetext();
			bridge.callHandler('gamepastetext',"",gamepastetext_callback);
		}catch(e){
			
		}
		return returnValue;
	}
	//获得市场id
	Func.getmarketname = function(){//
		//var returnValue = 1;
		//try{
			//return window.settings.getmarketname();
			//bridge.callHandler('getmarketname',"",getmarketname_callback
			//);
		//}catch(e){
		
		//}
		//return returnValue;
		//logmessage("market:"+app_market,1);
		return app_market;
	}
	Func.getInstallInfo = function(data){//
		if(!ConstVal.isGameHall){
			var returnValue = ifast_random(2);
			try{
				//var result = window.settings.getGameinstall(data);
				//return Number(result);
				bridge.callHandler('getGameinstall',data,function(resp){
						returnValue = Number(resp);
					}
				);
			}catch(e){
				//return ifast_random(2);
				
			}
			return returnValue;
		}else{
			return gameHallImport.isInstalled(data);
		}
	}
	/*
	{"body":"哈哈哈","price":1,"user":"sdsax11221","type":"ylniuniu001","typeplay":"1"}
	?user 用户id???
	type：yl+gamename+00N???列子：ylniuniu001?ylniuniu002
	?
	tpyealpay 支付类型 1 微信 2 支付宝
	body商品详情
	price 价格
	*/
	Func.getGamepay = function(data){//
		try{
			//window.settings.getGameplay(data);
			bridge.callHandler('getGameplay',"",function(resp){
					
				}
			);
		}catch(e){
			//var dt = JSON.parse(data);
			//PayuserPaytypePaystate(dt.playerid,dt.type,1,data.paytype,data)
		}
	}
	Func.getphonestate = function(){
		bridge.callHandler('getphonestate',"",function(resp){
		//主动调用返回通话状态
		
	       }
	    );

	}
	Func.ypayType = function(type){
		
		bridge.callHandler('ypayType',type,function(resp){
		//主动调用返回通话状态

	       }
	    );

	}
	
	//
	Func.SwitchOverGameData = function(webtype,Gamedirectory,gamedownloadurl,data){
		try{
			//window.settings.SwitchOverGameData(webtype,Gamedirectory,gamedownloadurl,data);
			var data={
				webtype:webtype,
				Gamedirectory:Gamedirectory,
				gamedownloadurl:gamedownloadurl,
				data:data
			};
			if(ConstVal.isGameHall){
				GameData.hallLogin = false;
				if(!gamedownloadurl || !Gamedirectory){
					gameHallImport.clearGameinfo();
					return;
				}
	
			}
			bridge.callHandler('SwitchOverGameData',data,function(resp){

				}
			);
		}catch(e){
			//console.log("webtype:"+webtype+"Gamedirectory:"+Gamedirectory+"gamedownloadurl:"+gamedownloadurl+"data:"+data);
		}
	}
	Func.backgameData = function(data){//
		try{
			//var data= {};
			//if(C_Player.roomcard>-1){
				//data.data = C_Player.returnHallData();
				//data.opt = "updatePlayerInfo";
				//data.from = 2;
				//data.gamename = app_gamename;
				//data.gameid = GameData.GameId;
				//Func.backgameData(JSON.stringify(data));
			//}else{
				//data.opt = "saveGameId";
				//data.from = 2;
				//data.gamename = app_gamename;
				//data.gameid = GameData.GameId;
				//Func.backgameData(JSON.stringify(data));
			//}
			bridge.callHandler('backgameData',data,function(resp){
					
				}
			);
		}catch(e){
	
		}
	}
	//开启定位
	Func.startlocation = function(type){
		try{
			//window.settings.startlocation(type);
			bridge.callHandler('startlocation',type,function(resp){

				}
			);
		}catch(e){
	
		}
	}
	//获取定位
	Func.getlocation = function(){
		try{
			if(GameData.otherLocation){
				GameData.otherLocationTimes++;
				if(GameData.otherLocationTimes > GameData.otherLocationAllTimes){
					return;
				}
			}
			//window.settings.getlocationinfo();
			bridge.callHandler('getlocationinfo',"",function(resp){

				}
			);
		}catch(e){
	
		}
	}
	Func.getchannelName = function(){//
		
		return app_channel;
	}
	
	//播放声音
	Func.play_wav = function(src,isloop){
		if(src){
			if(GameData.appstate ||(!GameData.appstate&&isloop==-1)){
				try{
					if(!GameData.isRecord){
						//window.settings.srcIsloop(src,isloop);
						var data = {
							src:src,
							isloop:isloop
						};
						bridge.callHandler('srcIsloop',data,function(resp){
								
							}
						);
					}
	
				}catch(e){
					if(!GameData.isRecord){
						play_wav(src,isloop);
					}
				}
			}
		}
	
	}
	
	//开启扫一扫
	Func.OpenScan = function(){
		try{
			//window.settings.opensaoma();
			bridge.callHandler('opensaoma',"",function(resp){

				}
			);
		}catch(e){
	
		}
	}
	Func.getVersionState = function(){
		
		return Number(app_appversion);
	}
	
	Func.startshake = function(){
		if(Utl.ReadData(Utl.Config.shake)==1){
			if(GameData.shakeID != Game_Config.shakeList.nil){
				try{
					//window.settings.startshake();
					bridge.callHandler('startshake','',function(resp){
							
				        }
				     );
				}catch(e){
	
				}
			}
		}
	}
	Func.stopshake = function(){
		try{
			//window.settings.stopshake();
			bridge.callHandler('stopshake','',function(resp){

		        }
		     );
		}catch(e){
	
		}
	}
	Func.switchshakeVoice = function(Voicetype){
		try{
			//window.settings.SwitchShake(Voicetype);
			bridge.callHandler('SwitchShake',Voicetype,function(resp){

		        }
		     );
		}catch(e){
	
		}
	}
	
	//分享图片（链接）
	Func.sharephotourl=function(sharetype,url){
		try{
			//window.settings.sharephotourl(sharetype,url);
			var data={
				sharetype:sharetype,
				url:url
			};
			bridge.callHandler('sharephotourl',data,function(resp){

		        }
		     );
		}catch(e){
			//alert(e);
		}
	}
	//获取网络类型 1 未连接网络  2 连接wifi  3 连接2G/3G/4G
	Func.getnetwork=function(){
	
		return app_getnetwork;
		
	}
	//获取wifi信号ssidname  wifi名称   signalLevel wifi信号强度 0-4 弱到强
	Func.getwifisignalLevel=function(){
		return Number(app_getwifisignalLevel);
	}
	//调用手机默认浏览器打开链接
	Func.browser=function(url){
		try{
			if(url){
				url = fixUrl(url);
				//window.settings.browser(url);
				bridge.callHandler('browser',url,function(resp){
					
			        }
			     );
			}
		}catch(e){
			console.log(url);
		}
	
	}
	//主动获取手机电量
	Func.getbattery=function(){
		
		return app_getbattery;
	}
	Func.mediaTypeAudio=function(audiourl,type,user){
	//因为游戏打包之前调用会报错，所以要使用try{}catch{}   try 里面 使用打包调用的函数 catch() 里面使用你自己的函数
		try{
			//window.settings.mediaTypeAudio(audiourl,type,v);
			var data = {
				audiourl:audiourl,
				type:type,
				user:user
			};
			bridge.callHandler('mediaTypeAudio',data,function(resp){
					
		        }
		     );
		}catch(e){
	
			// gameui_play_voice(v);
			//Net.submit_error("mediaAudio:audiourl="+audiourl+",type="+type+",user="+v,e.stack);
		}
	}
	
	Func.prepareAudio=function(){
	//因为游戏打包之前调用会报错，所以要使用try{}catch{}   try 里面 使用打包调用的函数 catch() 里面使用你自己的函数
		try{
			Utl.stopMusic();
			GameData.isRecord = true;
			//window.settings.prepareaudio();
			bridge.callHandler('prepareaudio',"",function(resp){

		        }
		     );
		}catch(e){
			//alert(e);
	
		}
	}
	//设置普通震动
	Func.vibrator=function(time){
		try{
			if(GameData.appstate){
				//window.settings.vibrator(time);
				bridge.callHandler('vibrator',time,function(resp){

			        }
			     );
			}
		}catch(e){
	
		}
	}
	//是否重复震动
	Func.repeatvibrator=function(repeat){
		try{
			if(GameData.appstate){
				//window.settings.repeatvibrator(repeat);
				bridge.callHandler('repeatvibrator',repeat,function(resp){

			        }
			     );
			}
		}catch(e){
	
		}
	}
	//取消震动
	Func.canclevibrator=function(){
		try{
			//window.settings.canclevibrator();
			bridge.callHandler('canclevibrator',"",function(resp){

		        }
		     );
		}catch(e){
	
		}
	}
	//横竖屏 orientation 1 为横屏  2 为竖屏
	Func.orientation=function(Orientation){
		try{
			//window.settings.orientation(Orientation);
			bridge.callHandler('orientation',Orientation,function(resp){

		        }
		     );
		}catch(e){
	
		}
	}
	//通知
	Func.notification=function(Ticker,title,content){
		//因为游戏打包之前调用会报错，所以要使用try{}catch{}   try 里面 使用打包调用的函数
		//var Ticker//手机状态栏通知
		//var title//标题
		//var content//内容
		try{
			//window.settings.notification(Ticker,title,content);
			var data={
				Ticker:Ticker,
				title:title,
				content:content
			};
			bridge.callHandler('notification',data,function(resp){

		        }
		     );
		}catch(e){
			
		}
	}
	
	

	Func.sharefriend=function(data){//1普通分享2截图分享3图片链接分享
		//因为游戏打包之前调用会报错，所以要使用try{}catch{}   try 里面 使用打包调用的函数 catch() 里面使用你自己的函数
			var sharefriend = data.sharefriend;
			var type = data.type;
			var webpageUrl = data.webpageUrl;
			var title = data.title;
			var description = data.description;
			var sharetype = data.sharetype;
			if(!sharetype){
				sharetype = 0;
			}
			if(!webpageUrl){webpageUrl = Game_Config.Share.appdownload;}
			if(GameData.gameData){
				webpageUrl = webpageUrl + "&gameData="+GameData.gameData;
				webpageUrl = fixUrl(webpageUrl);
			}
			if(!title){title = Game_Config.Share.title+Game_Config.Share.description;}
			//if(!description){description = }
			type == 2 ? GameData.shareFrom = 1 : GameData.shareFrom = 0;
			
			try{
				//window.settings.friendsSharetypeUrlToptitleDescript(sharefriend,type,webpageUrl,title,description);
				var data={
					sharefriend:sharefriend,
					type:type,
					webpageUrl:webpageUrl,
					title:title,
					description:description,
					sharetype:sharetype
				};
				bridge.callHandler('friendsSharetypeUrlToptitleDescript',data,function(resp){

				});
			}catch(e){
				//console.log("分享：sharefrind:"+sharefriend+"\ntype:"+type+"\nwebpageUrl:"+webpageUrl+"\ntitle:"+title+"\ndescription:"+description);
			}
			
			
		}

});
}
var shareLink=function shareLink(shareTimeline,shareAppMessage) {
var fenxiang = shareParam;
 var sid1= getQueryString('sid');
 var scode1= getQueryString('scode');

    var sidScode ={sid: sid1, scode: scode1};
    if(!sidScode) {
        
        return;
    }

    $.ajax({
               type: "post",
               url: "https://api.tscce.cn/api/weixin/wx_share_info",
               dataType: 'json',
               data: $.extend({}, sidScode, fenxiang),
               timeout: 1000 * 8,
               success: function (data, textStatus) {
                   //console.log('success', data);
                   if (data.error == 0) {
                       var js =
                           {
                               debug: false,
                               appId: data.data.appId, // ????????
                               timestamp: data.data.timestamp, // ????????
                               nonceStr: data.data.nonceStr, // ????????
                               signature: data.data.signature,// ??
                               jsApiList: [
                                   'onMenuShareTimeline',
                                   'onMenuShareAppMessage'
                               ]
                           }
                       wx.config(js);
                       wx.ready(function(){
				 

                           wx.onMenuShareTimeline({    //
                                                      title: shareTimeline.title,
                                                      link: shareTimeline.link,    // 
                                                      imgUrl: shareTimeline.imgUrl,    // 
                                                      success: function () {    // 
                                                      	sharesuccess(2,2);
                                                      	GameUI.closeShareImg();
                                                          //dialog.alert('分享朋友圈成功');
                                                      },
                                                      cancel: function () {   // 
                                                      	 GameUI.closeShareImg();
                                                      }
                                                  });

                           wx.onMenuShareAppMessage({    //?????
                                                        title: shareAppMessage.title,     // 
                                                        desc: shareAppMessage.desc,      // 
                                                        link: shareAppMessage.link,    // 
                                                        imgUrl: shareAppMessage.imgUrl,    //
                                                        type: 'link',
                                                        success: function () {    // 
                                                        	sharesuccess(2,1);
                                                        	GameUI.closeShareImg();
                                                            //dialog.alert('分享好友成功');
                                                        },
                                                        cancel: function () {   // 
                                                        	GameUI.closeShareImg();
                                                        }
                                                    });
                       });
                       wx.error(function(res){

                       });
                       return;
                   } else {
                       //alert(data.error_code + ': ' + data.msg);
				   sessionStorage.clear();
				   var code = parseInt(data.error_code);
				   if(data.error_code === 10001 || data.error_code === 10008 || data.error_code === 10011) {
						//getSidScode(wxLogin);
					}
                   }
               },
               complete: function (res) {
                   //console.log('complete',res);
               },
               error: function (XMLHttpRequest, textStatus, errorThrown) {
                   //console.log('error', XMLHttpRequest, textStatus, errorThrown);
                   //alert("错误");
               }
           });
}
Func.appDownload = function(url) {
	if(url){
		top.location=url;	
	}
		
}














































