function loadXMLDoc(method, url, callback, dataSub) {
	var xmlhttp = new XMLHttpRequest();
	var detail = "";
	var arr = [];
	for(var key in dataSub) {
		var row = key + "=" + dataSub[key];
		arr.push(row);
	}
	detail = arr.join("&");
	xmlhttp.onreadystatechange = function() {
		if(xmlhttp.readyState == XMLHttpRequest.DONE) {
			if(xmlhttp.status == 200) {
				callback(xmlhttp.responseText);
			} else if(xmlhttp.status == 400) {
				occMessage('There was an error 400');
			} else {
				occMessage('something else other than 200 was returned');
			}
		}
	};
	if(method == "GET") {
		if(detail.length > 0) {
			url = url + "?" + detail;
			detail = null;
		}
		xmlhttp.open("GET", baseURL()+url, true);
	} else if(method == "POST") {
		xmlhttp.open("POST", baseURL()+url, true);
	}

	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	if(window.IAObj) {
		xmlhttp.setRequestHeader("Authorization", window.IAObj.getJwt());
	} else {
		xmlhttp.setRequestHeader("Authorization", "Bearer " + getParam('Authorization'));
	}
	xmlhttp.send(detail);
}
function baseURL(){
	if(window.IAObj){
		return window.IAObj.getBaseUrl();
	}else {
		return "http://test.engdd.com";
	}
}
function getParam(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if(r != null) return unescape(r[2]);
	return null;
}

function exit() {
	//dir:0发起者，1接受者
	//通讯命令:0开始
	if(checkClient()) {
		var IAMsg = {
			cmd: "24"
		};
		var tJSon = JSON.stringify(IAMsg);
		//jsonz字符串
		IAObj.jsSendCmdJsonStr(tJSon);
	} else {
		alert("未定义客户端桥");
	}
}
function getClientUserId()
{
    if (checkClient()) {
      	return  IAObj.getUserInfo()["userId"];
    }else{
    	return  getParam("loginId");
    }
}

function checkClient() {
	var rClient = false;
	if(typeof(IAObj) != "undefined") {
		rClient = true;
	} else {
		rClient = false;
	}
	return rClient;
}

function occMessage(str) {
	var message = document.querySelector(".message");
	message.opacity = 0;
	message.innerHTML = str;
	setTimeout(function() {
		message.style.display = "block";
	}, false)
	message.speed = 0.05;
	message.timer = requestAnimationFrame(render_message);

	function render_message() {
		if(message.opacity <= 1 && message.speed >= 0) {
			message.opacity += message.speed;
			message.style.opacity = message.opacity;
			message.timer = requestAnimationFrame(render_message);
		} else {
			setTimeout(function() {
				message.style.display = "none";
				message.style.opacity = 0;
			}, 500)
		}
	}
}
var boxMessage = {
	sleep_envelopes_count: 0,
	sleep_envelopes_money: 0,
	wake_envelopes_count: 0,
	wake_envelopes_money: 0,
	envelopes_count: 20,
	total_money: 2000,
	move_status: 0,
	maxMoney:0,
	boxes: [{
		id: 1,
		cost: 0,
		valid: true
	}, {
		id: 2,
		cost: 1,
		valid: true
	}, {
		id: 1,
		cost: 0,
		valid: true
	}, {
		id: 2,
		cost: 1,
		valid: true
	}, {
		id: 1,
		cost: 0,
		valid: true
	}, {
		id: 2,
		cost: 1,
		valid: true
	}, {
		id: 1,
		cost: 0,
		valid: true
	}, {
		id: 2,
		cost: 1,
		valid: true
	}, {
		id: 1,
		cost: 0,
		valid: true
	}, {
		id: 2,
		cost: 1,
		valid: true
	}, {
		id: 1,
		cost: 0,
		valid: true
	}, {
		id: 2,
		cost: 1,
		valid: true
	}],
	nowBox: {

	},
	_history:[],
	biggest:{}
};
var charRoom = "";

function renderBox() {
	var boxAllIn = document.querySelector(".boxAllInCon");
	var boxstr = "";
	var j = 0;
	for(var i = 0; i < boxMessage.boxes.length; i++) {
		if(i % 49 == 0) {
			var strcell = "";
		}
		if(boxMessage.boxes[i].cost == 0) {
			if(boxMessage.boxes[i].valid == true){
				var str = '<div class="boxCell1 boxCell" onclick = "openFree(' + boxMessage.boxes[i].id + ',' + boxMessage.boxes[i].cost + ','+i+')" boxid =' + boxMessage.boxes[i].id + '></div>';
			}else {
				var str = '<div class="boxCell1Close boxCell" onclick = "openFree(' + boxMessage.boxes[i].id + ',' + boxMessage.boxes[i].cost + ','+i+')" boxid =' + boxMessage.boxes[i].id + '></div>';
			}
			
		} else {
			if(boxMessage.boxes[i].valid == true){
				var str = '<div class="boxCell2 boxCell" onclick = "openFree(' + boxMessage.boxes[i].id + ',' + boxMessage.boxes[i].cost + ','+i+')" boxid =' + boxMessage.boxes[i].id + '><span>' + boxMessage.boxes[i].cost + '</span></div>';
			}else {
				var str = '<div class="boxCell2Close boxCell" onclick = "openFree(' + boxMessage.boxes[i].id + ',' + boxMessage.boxes[i].cost + ','+i+')" boxid =' + boxMessage.boxes[i].id + '><span>' + boxMessage.boxes[i].cost + '</span></div>';
			}
			
		}
		strcell += str;
		if(i % 49 == 48) {
			strcell = '<div class="contentarea" onclick =contentareaposition(' + j + ')>' + strcell + '</div>';
			j++;
			boxstr += strcell;
		}
	}
	boxAllIn.innerHTML = boxstr;
	setTimeout(function(){
		setScrollBoxAll();
	},0)
}
var u = navigator.userAgent;
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
document.querySelector("#chatroom").onfocus = function() {
	if(isiOS) {
		document.querySelector(".inputdeal").style.display = "block";
		setTimeout(function() {
			container.scrollTop = window.innerWidth * 93 / 20 - window.innerHeight;
		}, 0);
	}else {
		container.scrollTop = 9999;
	}
}
document.querySelector("#chatroom").onblur = function() {
	if(isiOS) {
		document.querySelector(".inputdeal").style.display = "none";
	}
}
document.getElementById("inputPhone").onfocus = function(){
	if(isiOS) {
		document.querySelector(".fixinput").style.display = "block";
		setTimeout(function() {
			document.getElementById("cardInfoDiv").scrollTop = window.innerWidth * 93 / 20 - window.innerHeight;
		}, 0);
	}else {
		document.getElementById("cardInfoDiv").scrollTop = 9999;
	}
}
document.getElementById("inputPhone").onblur = function() {
	if(isiOS) {
		document.querySelector(".fixinput").style.display = "none";
	}
}
var source = null;
function renderhistory(){
	var chatroomsection = document.querySelector(".chatRoomSection");
	for(var i = 0 ; i < boxMessage._history.length ; i ++){
		var p = document.createElement("p");
		p.innerHTML = "<span>" + boxMessage._history[boxMessage._history.length-1-i].timestamp + "</span><span>" + boxMessage._history[boxMessage._history.length-1-i].chat + "</span>";
		chatroomsection.appendChild(p);
	}
	setTimeout(function(){
		document.querySelector(".chatRoom").scrollTop = 5000;
	},0)
}
function getBoxStatus() {
	loadXMLDoc("GET", "/game_server/box_package/box/", function(data) {
		var back = JSON.parse(data);
		if(back.ok == true) {
			boxMessage.boxes = back["boxes"];
			boxMessage.sleep_envelopes_count = back.sleep_envelopes_count;
			boxMessage.sleep_envelopes_money = back.sleep_envelopes_money;
			boxMessage.wake_envelopes_count = back.wake_envelopes_count;
			boxMessage.wake_envelopes_money = back.wake_envelopes_money;
			boxMessage._history = back.history;
			boxMessage.maxMoney = back.biggest_money;
			document.getElementById("maxMoney").innerHTML = toDecimal2((boxMessage.maxMoney/100));
			document.querySelector(".brStatus").innerHTML = '<p>有' + back.sleep_envelopes_count + '个红包(共' + (back.sleep_envelopes_money / 100) + '元)还在红包箱里睡觉，等你发现和转移。</p><p>有' + back.wake_envelopes_count + '个红包(共' + (back.wake_envelopes_money / 100) + '元)已睡醒，快去把红包抱回家吧！</p>';
			renderBox();
			renderhistory();

			source = new EventSource(baseURL()+'/game_server_sse/box_package_' + boxMessage.boxes[0].game.id + '/');
			var chatRoom = document.querySelector(".chatRoomSection");
			source.addEventListener('delta', function(e) {
				//	app.trigger("view:update", e.data);
				//				console.log(["delta",e]);
				var chatobj = JSON.parse(e.data);
				var str = chatobj.chat;
				str = decodeUTF8(str);
				var time = chatobj.timestamp;
				var p = document.createElement("p");
				p.innerHTML = "<span>" + time + "</span><span>" + str + "</span>";
				chatRoom.appendChild(p);
				setTimeout(function() {
						var chatDiv = document.querySelector(".chatRoom");
						chatDiv.scrollTop = chatRoom.offsetHeight - chatDiv.offsetHeight;
					}, 0)
					//刷新红包数据
				if(chatobj.statistic) {
					boxMessage.sleep_envelopes_count = chatobj.statistic.sleep_envelopes_count;
					boxMessage.sleep_envelopes_money = chatobj.statistic.sleep_envelopes_money;
					boxMessage.wake_envelopes_count = chatobj.statistic.wake_envelopes_count;
					boxMessage.wake_envelopes_money = chatobj.statistic.wake_envelopes_money;
					boxMessage.maxMoney = chatobj.statistic.biggest_money;
					document.getElementById("maxMoney").innerHTML = toDecimal2((boxMessage.maxMoney/100));
					document.querySelector(".brStatus").innerHTML = '<p>有' + boxMessage.sleep_envelopes_count + '个红包(共' + (boxMessage.sleep_envelopes_money / 100) + '元)还在红包箱里睡觉，等你发现和转移。</p><p>有' + boxMessage.wake_envelopes_count + '个红包(共' + (boxMessage.wake_envelopes_money / 100) + '元)已睡醒，快去把红包抱回家吧！</p>';
					occportMessage(str);
				}
			}, false);
			source.addEventListener('error', function(e) {
				if(e.readyState == EventSource.CLOSED) {
					console.log(["e.readyState == EventSource.CLOSED", e]);
					occMessage("EventSource error")
				} else if(e.readyState == EventSource.OPEN) {
					console.log(["e.readyState == EventSource.OPEN", e]);
					occMessage("EventSource error")
				}
			}, false);
		} else {
			//請求失敗
			occMessage("获取箱子的状态失败");
		}
	}, {});
}

function openBox(index) {
	var box = boxMessage.boxes[index];
	//免费并且可以直接打开的箱子 
	loadXMLDoc("POST", "/game_server/box_package/box/" + index + "/ ", function(data) {
		var back = JSON.parse(data);
		if(back.ok == true) {
			boxMessage.nowBox = back.envelope;
			boxMessage.key = back.key;
			boxMessage.index = index;
			//接下来显示提示窗口
			findMoneyBag();
		} else if(back.error == "too_frequently") {
			//直接打开免费箱子出错
			occMessage("手太快了，稍微慢一些。");
		}else if(back.error == "exceed_limit"){
			occMessage("你今天已经打开足够多的箱子了。");
		}else{
			occMessage("打开免费箱子失败");
		}
	}, {
		
	});
	cancelbox();
	if(boxMessage.biggest.length != 0 && boxMessage.biggest.id == index){
		document.querySelector("#maxNumLight").style.display = "none";
	}
}

function payBox(index) {
	loadXMLDoc("POST", "/game_server/box_package/box/" + index + "/ ", function(data) {
		var back = JSON.parse(data);
		if(back.ok == true) {
			boxMessage.nowBox = back.envelope;
			boxMessage.key = back.key;
			boxMessage.index = index;
			findMoneyBag();
		} else if(back.error == "pay_faild") {
			//支付失败
			occMessage("支付失败:"+encodeUTF8(back.msg));
		} else if(back.error == "exceed_limit"){
			occMessage("你今天已经打开足够多的箱子了");
		}
		cancelbox();
	}, {
		
	})
}

function findMoneyBag() {
	if(boxMessage.nowBox == null) {
		//没有红包
		opennone();
	} else {
		if(boxMessage.nowBox.can_be_taken == false) {
			//			需要等待的红包
			document.querySelector(".explainDiv p:nth-of-type(2)").innerHTML = "红包将于" + boxMessage.nowBox.next_awake_at + "醒来，记得来抱走。";
			abshide.style.display = "block";
			waitMoney(1);
		} else if(boxMessage.nowBox.can_be_taken == true) {
			//可以直接领的红包
			//			getMoney();
			abshide.style.display = "block";
			document.querySelector(".explainDiv p:nth-of-type(2)").innerHTML = "红包可以直接领取。";
			waitMoney(0);
		}
	}
}

function orderMove() {
	cancelfoundmoney();
	boxMessage.move_status = 1;

	document.querySelector(".section").style.backgroundColor = "black";
}

function getMoney() {
	cancelfoundmoney();
	loadXMLDoc("POST", "/game_server/box_package/envelope/" + boxMessage.nowBox.id + "/ ", function(data) {
		var back = JSON.parse(data);
		if(back.ok == true) {
			//领红包成功
			findMoney();
		} else {
			if(back.error == "envelope_is_sleep") {
				bemove(2);
			} else if(back.error == "envelope_not_valid") {
				bemove(1);
			}else {
				occMessage("caiwuBUG");
			}
			//			occMessage("领出红包错误");
		}
	}, {
		box_id:boxMessage.index,
		key:boxMessage.key
	});
}

function opennone() {
	document.querySelector(".findnone").style.display = "block";
	var noneDiv = document.querySelector(".findnoneimg");
	noneDiv.style.backgroundImage = "url(img/XZDH-1.png)";
	noneDiv.className = "findnoneimg occport";
	noneDiv.style.display = "block";
	setTimeout(function() {
		noneDiv.className = "findnoneimg";
		noneDiv.style.display = "block";
	}, 250);
	setTimeout(function() {
		noneDiv.style.backgroundImage = "url(img/XZDH-2.png)";
		noneDiv.onclick = function() {
			cancelopennone();
		}
	}, 1000);
}

function cancelopennone() {
	var noneDiv = document.querySelector(".findnoneimg");
	noneDiv.className = "findnoneimg appearport";
	setTimeout(function() {
		document.querySelector(".findnone").style.display = "none";
		noneDiv.style.display = "none";
		noneDiv.className = "findnoneimg";
		abshide.style.display = "none";
	}, 250);
}

function findMoney() {
	var findDiv = document.querySelector(".findMoney");
	abshide.style.display = "block";
	findDiv.style.display = "block";
	findDiv.style.opacity = 1;
	if(boxMessage.nowBox.packer == null){
		findDiv.querySelector(".findMoney_text").innerHTML = "感谢亲亲我家为你送来的红包";	
	}else {
		findDiv.querySelector(".findMoney_text").innerHTML = "感谢"+boxMessage.nowBox.packer.real_name+"为你送来的红包";	
	}
	findDiv.querySelector(".findMoney_num span:nth-of-type(1)").innerHTML = boxMessage.nowBox.money / 100;
}

function cancelfindmoney() {
	var findDiv = document.querySelector(".findMoney");
	findDiv.style.opacity = 0;
	setTimeout(function() {
		findDiv.style.display = "none";
		abshide.style.display = "none";
	}, 450)
}
var foundtimer = null;
//var wakeup = 0;
function waitMoney(index) {
	document.querySelector(".waitMoney").style.display = "block";
	var waitDiv = document.querySelector(".waitMoneyimg");
	waitDiv.className = "waitMoneyimg occport";
	//	waitDiv.querySelector(".waitNum").innerHTML = boxMessage.nowBox.money;
	//	waitDiv.querySelector(".waitTime").innerHTML = boxMessage.nowBox.wait_time;
	clearInterval(foundtimer);
	foundtimer = null;
	waitDiv.style.display = "block";
	setTimeout(function() {
		waitDiv.className = "waitMoneyimg";
		waitDiv.style.display = "block";
	}, 250);
	setTimeout(function() {
		waitDiv.style.backgroundImage = "url(img/XZDH-3.png)";
	}, 350);

	if(index == 1) {
		setTimeout(function() {
			//需要等待的红包
			waitDiv.style.display = "none";
			document.querySelector(".waitMoney").style.display = "none";
			waitDiv.className = "waitMoneyimg";
			var foundMoney = document.querySelector(".foundMoney");
			foundMoney.querySelector(".foundtitle").style.backgroundImage = "url(img/HBshui.png)";
			foundMoney.querySelector(".foundtitle").onclick = function() {
				null;
			}
			foundMoney.querySelector(".foundtitlebg").style.display = "none";
			foundMoney.querySelector(".explain_found").innerHTML = "哇！发现一个沉睡中的BR红包";
			foundMoney.querySelector(".found_time").style.display = "inline-block";
			var foundtime = foundMoney.querySelector(".found_time span:nth-of-type(1)");
			var foundnumclock = parseInt(boxMessage.nowBox.wait_time);
			wakeup = foundnumclock;
			if(foundnumclock >= 86400) {
				clearInterval(foundtimer);
				foundtimer = null;
				foundtime.innerHTML = "超过一天";
			} else {
				clearInterval(foundtimer);
				foundtimer = null;
				var hour = parseInt(foundnumclock / 3600);
				hour < 10 ? hour = "0" + hour : null;
				var min = parseInt(foundnumclock % 3600 / 60);
				min < 10 ? hour = "0" + min : null;
				var sec = parseInt(foundnumclock % 3600 % 60);
				sec < 10 ? hour = "0" + sec : null;
				foundtime.innerHTML = hour + ":" + min + ":" + sec;
				foundtimer = setInterval(function() {
					foundnumclock--;
					var hour = parseInt(foundnumclock / 3600);
					hour < 10 ? hour = "0" + hour : null;
					var min = parseInt(foundnumclock % 3600 / 60);
					min < 10 ? min = "0" + min : null;
					var sec = parseInt(foundnumclock % 3600 % 60);
					sec < 10 ? sec = "0" + sec : null;
					foundtime.innerHTML = hour + ":" + min + ":" + sec;
					if(foundnumclock <= 0) {
						//红包可以领了
						clearInterval(foundtimer);
						foundtimer = null;
						foundMoney.querySelector(".foundtitle").style.backgroundImage = "url(img/HBxing.png)";
						foundMoney.querySelector(".foundtitle").onclick = function() {
							getMoney();
						}
						foundMoney.querySelector(".foundtitlebg").style.display = "block";
						foundMoney.querySelector(".explain_found").innerHTML = "红包醒了，请点击抱走！";
						foundMoney.querySelector(".found_time").style.display = "none";

					}
				}, 1000);
			}
			foundMoney.querySelector(".found_num span:nth-of-type(1)").innerHTML = (boxMessage.nowBox.money) / 100;
			foundMoney.style.display = "block";
			setTimeout(function() {
				foundMoney.style.opacity = 1;
			}, 0)
		}, 1000);
	} else {
		setTimeout(function() {
			//			可以直接领走的红包
			waitDiv.style.display = "none";
			document.querySelector(".waitMoney").style.display = "none";
			waitDiv.className = "waitMoneyimg";
			var foundMoney = document.querySelector(".foundMoney");
			foundMoney.querySelector(".foundtitlebg").style.display = "block";
			foundMoney.querySelector(".foundtitle").style.backgroundImage = "url(img/HBxing.png)";
			foundMoney.querySelector(".explain_found").innerHTML = "红包醒了，请点击抱走！";
			foundMoney.querySelector(".foundtitle").onclick = function() {
				getMoney();
			}
			foundMoney.querySelector(".found_time").style.display = "none";
			foundMoney.querySelector(".found_num span:nth-of-type(1)").innerHTML = (boxMessage.nowBox.money) / 100;
			foundMoney.style.display = "block";
			setTimeout(function() {
				foundMoney.style.opacity = 1;
			}, 0)
		}, 1000);
	}

}

function cancelfoundmoney() {
	var foundMoney = document.querySelector(".foundMoney");
	clearInterval(foundtimer);
	foundtimer = null;
	foundMoney.style.opacity = 0;
	setTimeout(function() {
		foundMoney.style.display = "none";
		abshide.style.display = "none";
		document.querySelector(".waitMoney").style.display = "none";
	}, 450);
}

function cancelwaitmoney() {
	var waitDiv = document.querySelector(".waitMoneyimg");
	waitDiv.className = "waitMoneyimg appearport";
	setTimeout(function() {
		waitDiv.className = "waitMoneyimg";
		waitDiv.style.display = "none";
		waitDiv.style.backgroundImage = "url(img/XZDH-1.png)";
	}, 250);
}
var toboxid = [0, 0];
var abshide = document.querySelector(".abshide");

function openFree(index, cost,i) {
	//	Math.abs(document.body.scrollTop - (window.innerHeight /4))<20 ? null:document.body.scrollTop = (window.innerHeight /4);
	if(boxMessage.move_status == 0) {
		if(boxMessage.boxes[i].valid == true){
			var openbox = document.querySelector(".openFree");
			if(cost == 0) {
				//			openbox.innerHTML = '<div class="openTitle">你找到了一个免费的箱子，打开看看里面有什么？</div><div class="openFreeCon"><div class="open" onclick="openBox(' + index + ')">打开它</div><div class="cancel" onclick="cancelbox()">挑个别的</div></div>';
				openBox(index);
			} else if(cost != 0) {
				//			openbox.innerHTML = '<div class="openTitle">你找到了一个付费的箱子，打开需要花费' + cost + '亲亲指数或红包，打开看看？</div><div class="openFreeCon"><div class="open" onclick="payBox(' + index + ')">打开它</div><div class="cancel" onclick="cancelbox()">挑个别的</div></div>';
				openbox.innerHTML = '<div class="opencontent"><div>打开此箱子需要使用' + cost + '个亲亲指数或' + cost + '分红包账户。</div></div><div class="openFreecon"><div class="cancel" onclick="cancelbox()">取消</div><div class="open" onclick="payBox(' + index + ')">确定</div></div>'
				openbox.style.display = "block";
				openbox.className = "openFree occport";
				setTimeout(function() {
					openbox.className = "openFree";
					openbox.style.display = "block";
				}, 250);
			}
		}else {
			occMessage("此区域暂未开放");
		}
	} else if(boxMessage.move_status == 1) {
		toboxid = [index, cost];
		moveTipFunc();
	}
}

function cancelbox() {
	var openbox = document.querySelector(".openFree");
	openbox.className = "openFree appearport";
	setTimeout(function() {
		openbox.className = "openFree";
		openbox.style.display = "none";
	}, 250);
}

function moveBagDiv() {
	var movebag = document.querySelector(".moveBag");
	movebag.style.display = "block";
	movebag.className = "moveBag occport";
	setTimeout(function() {
		movebag.className = "moveBag";
		movebag.style.display = "block";
	}, 250)
}

function cancelMove() {
	var movebag = document.querySelector(".moveBag");
	movebag.className = "moveBag appearport";
	setTimeout(function() {
		movebag.style.display = "none";
		movebag.className = "moveBag";
	}, 250)
}

function sendMessage() {
	var chatroom = document.getElementById("chatroom");
	var msg = chatroom.value;
	if(msg.length > 1 && msg.length < 100) {
		loadXMLDoc("POST", "/game_server/box_package/send_msg/", function(data) {
			var back = JSON.parse(data);
			if(back.ok == true) {
				chatroom.value = "";
			} else {
				occMessage("发送信息失败")
			}
		}, {
			"msg": msg
		});
	} else {
		occMessage("过长或过短的发言");
	}
}
///game_server_sse/box_package/

function encodeUTF8(str) {
	var temp = "",
		rs = "";
	for(var i = 0, len = str.length; i < len; i++) {
		temp = str.charCodeAt(i).toString(16);
		rs += "\\u" + new Array(5 - temp.length).join("0") + temp;
	}
	return rs;
}

function decodeUTF8(str) {
	return str.replace(/(\\u)(\w{4}|\w{2})/gi, function($0, $1, $2) {
		return String.fromCharCode(parseInt($2, 16));
	});
}

function moveTipFunc() {

	var moveTipDiv = document.querySelector(".movetip");
	if(toboxid[1] == 0) {
		moveTipDiv.querySelector(".explainDiv:nth-of-type(2)").style.display = "none";
	} else {
		moveTipDiv.querySelector(".explainDiv:nth-of-type(2)").innerHTML = '再次打开此箱时，需要使用' + toboxid[1] + '个亲亲指数或' + toboxid[1] + '分红包账户。';
		moveTipDiv.querySelector(".explainDiv:nth-of-type(2)").style.display = "block";
	}
	moveTipDiv.style.display = "block";
	moveTipDiv.className = "movetip occport";
	setTimeout(function() {
		moveTipDiv.className = "movetip";
		moveTipDiv.style.display = "block";
	}, 250);

}

function cancelmovetipDiv() {
	var moveTipDiv = document.querySelector(".movetip");
	moveTipDiv.className = "movetip appearport";
	setTimeout(function() {
		moveTipDiv.style.display = "none";
		moveTipDiv.className = "movetip";
	}, 250);
}

function tomove() {
	cancelmovetipDiv();
	loadXMLDoc("POST", "/game_server/box_package/box/" + boxMessage.nowBox.box.id + "/move/", function(data) {
		var back = JSON.parse(data);
		if(back.ok == true) {
			//				moveBagDiv();
		} else if(back.error = "too_frequently") {
			bemove(3);
			
		} else {
			bemove(1);
		}
		document.querySelector(".section").style.backgroundColor = "#821A35";
		boxMessage.move_status = 0;
	}, {
		to: toboxid[0]
	});
}

function bemove(index) {
	var bemoveDiv = document.querySelector(".bemove");
	if(index == 1) {
		bemoveDiv.querySelector("p:nth-of-type(1)").innerHTML = "手慢了！";
		bemoveDiv.querySelector("p:nth-of-type(2)").innerHTML = "已经被他人抱走了！";
	} else if(index == 2) {
		bemoveDiv.querySelector("p:nth-of-type(1)").innerHTML = "手慢了！";
		bemoveDiv.querySelector("p:nth-of-type(2)").innerHTML = "BR红包醒来发现没有被理会，又昏昏睡去了。";
	} else if(index == 3) {
		bemoveDiv.querySelector("p:nth-of-type(1)").innerHTML = "心疼一下BR红包嘛。";
		bemoveDiv.querySelector("p:nth-of-type(2)").innerHTML = "BR红包刚刚换了家，还没有想走的欲望。<br>(一分钟之内br红包不想多次搬家)";
	}
	bemoveDiv.style.display = "block";
	setTimeout(function() {
		bemoveDiv.style.opacity = 1;
		abshide.style.display = "block";
	}, 0)
}

function cancelbemove() {
	var bemoveDiv = document.querySelector(".bemove");
	bemoveDiv.style.display = "none";
	bemoveDiv.style.opacity = 0;
	abshide.style.display = "none";
}
//发红包
function fahongbao() {
	var pushredbagDiv = document.querySelector(".pushredbag");
	pushredbagDiv.style.display = "block";
	setTimeout(function() {
		pushredbagDiv.style.opacity = 1;
		pushredbagDiv.style.display = "block";
		abshide.style.display = "block";
	}, 0)
}

function cancelfa() {
	var pushredbagDiv = document.querySelector(".pushredbag");
	pushredbagDiv.style.opacity = 0;
	setTimeout(function() {
		var inputAll = document.querySelectorAll(".pushredbag input");
		for(var i = 0; i < inputAll.length; i++) {
			inputAll[i].value = null;
		}
		pushredbagDiv.style.display = "none";
		abshide.style.display = "none";
		hasBeenSubmit = false;
	}, 250)
}
var hasBeenSubmit = false;

function makesureSubmit() {
	var value_num = document.querySelector(".pushred_num input").value;
	var value_count = document.querySelector(".pushred_count input").value * 100;
	if(value_num % 1 == 0 && value_count % 1 == 0 && value_num > 0 && value_num > 0) {
		if(value_num <= 10 && value_count >= value_num && hasBeenSubmit == false) {
			if(value_count < 100000000){
				hasBeenSubmit = true;
				loadXMLDoc("POST", "/game_server/box_package/put_envelope/", function(data) {
					var back = JSON.parse(data);
					if(back.ok == true) {
						occMessage("红包已成功放入奖池");
						cancelfa();
					} else {
						occMessage(back.msg);
					}
					hasBeenSubmit = false;
				}, {
					amount: value_count,
					count: value_num
				})
			}else {
				occMessage("红包太大了，箱子放不下。");
			}
		} else {
			occMessage("请保证红包少于十个并至少每个红包都有金额");
		}

	} else {
		occMessage("请输入正确的红包信息")
	}
};
var inrank = 0;

function occrank(index) {
	if(index != inrank) {
		inrank = index;
		var rankSection = document.querySelector(".rank_section");
		//		rankSection.style.display = "block";
		if(index == 1) {
			//发红包排行
			var rankTitleSpan = rankSection.querySelectorAll(".rank_title span");
			rankTitleSpan[0].style.borderBottom = "0.1rem solid white";
			rankTitleSpan[1].style.borderBottom = 0;
			loadXMLDoc("GET", "/game_server/box_package/toplist/", function(data) {
				var back = JSON.parse(data);
				if(back.ok == true) {
					var rank_paker = back.top_packer;
					var rankpakerStr = "";
					var rankList = document.querySelector(".rank_list");
					//					console.log(rank_paker);
					for(var i = 0; i < rank_paker.length; i++) {
						var str = '<div class="rankCell"><span>' + (i + 1) + '</span><span style="background-image:url(' + rank_paker[i].packer.avatar + ')"></span><span>' + rank_paker[i].packer.real_name + '</span><span>' + rank_paker[i].count + '</span><span>' + toDecimal2(rank_paker[i].money / 100) + '</span></div>';
						//						console.log(str);
						rankpakerStr = rankpakerStr + str;
					}
					rankList.innerHTML = rankpakerStr;
					rankSection.style.display = "block";
					abshide.style.display = "block";
				} else {
					occMessage(back.msg)
				}
			}, {})
		} else if(index == 2) {
			var rankTitleSpan = rankSection.querySelectorAll(".rank_title span");
			rankTitleSpan[1].style.borderBottom = "0.1rem solid white";
			rankTitleSpan[0].style.borderBottom = 0;
			loadXMLDoc("GET", "/game_server/box_package/toplist/", function(data) {
				var back = JSON.parse(data);
				if(back.ok == true) {
					var rank_paker = back.top_taker;
					var rankpakerStr = "";
					var rankList = document.querySelector(".rank_list");
					for(var i = 0; i < rank_paker.length; i++) {
						var str = '<div class="rankCell"><span>' + (i + 1) + '</span><span style="background-image:url(' + rank_paker[i].taker.avatar + ')"></span><span>' + rank_paker[i].taker.real_name + '</span><span>' + rank_paker[i].count + '</span><span>' + toDecimal2(rank_paker[i].money / 100) + '</span></div>';
						rankpakerStr = rankpakerStr + str;
					}
					rankList.innerHTML = rankpakerStr;
					rankSection.style.display = "block";
					abshide.style.display = "block";
				} else {
					occMessage(back.msg)
				}
			}, {})
		}

	}
}

function cancelRank() {
	var rankSection = document.querySelector(".rank_section");
	rankSection.style.display = "none";
	abshide.style.display = "none";
	inrank = 0;
}
var portMessage = document.querySelector(".portMessage");

function occportMessage(str) {
	portMessage.style.display = "block";
	var p = document.createElement("p");
	p.className = "anip";
	p.innerHTML = str;
	portMessage.appendChild(p);
	p.addEventListener("webkitAnimationEnd", function() {
		p.parentNode.removeChild(p);
		setTimeout(function() {
			if(portMessage.innerHTML == null) {
				portMessage.style.display = "none";
			}
		}, 0)
	});
}
var prestatus = 0;

function betterView() {
	if(boxMessage.move_status != 3){
		var boxall = document.querySelector(".boxAll");
		var boxallIn = document.querySelector(".boxAllIn");
		var boxcellAll = document.querySelectorAll(".boxCell1");
		for(var i = 0; i < boxcellAll.length; i++) {
			boxcellAll[i].style.opacity = 0.2;
		}
		boxallIn.style.webkitTransform = "scale(0.33,0.33) translate(0,0)";
		boxallIn.style.transform = "scale(0.33,0.33) translate(0,0)";
		prestatus = boxMessage.move_status;
		boxMessage.move_status = 3;
		boxall.scrollTop = 0;
		boxall.scrollLeft = 0;	
	}
	
}
document.querySelector("#container").style.height = window.innerHeight + "px";
var contentArr = [[0,0],[-19,0],[-38,0],[0,-19],[-19,-19],[-38,-19],[0,-38],[-19,-38],[-38,-38]];


function contentareaposition(index) {
	if(boxMessage.move_status == 3) {
		var boxallIn = document.querySelector(".boxAllIn");
		boxallIn.style.transition = "all 0.4s linear";
		boxallIn.style.webkitTransform = "scale(1,1) translate(" + contentArr[index][0] +"rem," + contentArr[index][1]+ "rem)";
		boxallIn.style.transform = "scale(1,1) translate(" + contentArr[index][0] +"rem," + contentArr[index][1]+ "rem)";
		boxMessage.move_status = prestatus;
		boxAllIn.saveX = contentArr[index][0] * window.innerWidth / 20;
		boxAllIn.saveY = contentArr[index][1] * window.innerWidth / 20;
		var boxcellAll = document.querySelectorAll(".boxCell1");
		for(var i = 0; i < boxcellAll.length; i++) {
			boxcellAll[i].style.opacity = 1;
		}
	}
	if(firstCon == false){
		firstCon = true;
	}
}
var scrollNow = [0,0];
var boxAllIn = document.querySelector(".boxAllIn");
boxAllIn.saveX = 0;
boxAllIn.saveY = 0;
function setScrollBoxAll(){
	boxAllIn.addEventListener("touchstart",function(e){
		if(boxMessage.move_status != 3){
			boxAllIn.style.transition = "all 0s linear";
//			e.preventDefault();
			boxAllIn.preX = e.touches[0].clientX;
			boxAllIn.preY = e.touches[0].clientY;
		}
	},false);
	boxAllIn.addEventListener("touchmove",function(e){
		e.preventDefault();
		if(boxMessage.move_status != 3){
			this.disX =  -this.preX + e.touches[0].clientX + this.saveX;
			this.disY =  -this.preY + e.touches[0].clientY + this.saveY;
			this.disX > 0 ? this.disX = 0:null;
			this.disX < ( - 1 * 1.9*window.innerWidth) ? this.disX = (-1.9*window.innerWidth) : null;
			this.disY > 0 ? this.disY = 0:null;
			this.disY < ( - 1 * 1.9*window.innerWidth) ? this.disY = (-1.9*window.innerWidth) : null;
			boxAllIn.style.webkitTransform = "scale(1,1) translate(" + this.disX +"px," + this.disY + "px)";
			boxAllIn.style.transform = "scale(1,1) translate(" + this.disX +"px," + this.disY + "px)";
		}
	},false);
	boxAllIn.addEventListener("touchend",function(){
		if(boxMessage.move_status != 3){
			this.saveX = this.disX;
			this.saveY = this.disY;
			boxAllIn.style.transition = "all 0.4s linear";
		}
	},false);
}


function occhelp() {
	var gamehelp = document.querySelector(".gamehelp");
	gamehelp.style.display = "block";
	setTimeout(function() {
		gamehelp.style.opacity = 1;
	}, 0)
}

function cancelhelp() {
	var gamehelp = document.querySelector(".gamehelp");
	gamehelp.style.opacity = 0;
	setTimeout(function() {
		gamehelp.style.display = "none";
	}, 280);
}

function toDecimal2(x) {
	var f = parseFloat(x);
	if(isNaN(f)) {
		return false;
	}
	var f = Math.round(x * 100) / 100;
	var s = f.toString();
	var rs = s.indexOf('.');
	if(rs < 0) {
		rs = s.length;
		s += '.';
	}
	while(s.length <= rs + 2) {
		s += '0';
	}
	return s;
}
var firstCon = false;
setTimeout(function(){
	betterView();
	setTimeout(function(){
		if(firstCon == false){
			contentareaposition(parseInt(Math.random()*8));
		}
	},3000)
},0)

function occLarge(){
	var largeDiv = document.querySelector(".largeNum");
	largeDiv.querySelector(".submitType1").style.display = "block";
	largeDiv.querySelector(".submitType2").style.display = "none";
	largeDiv.style.display = "block";
	setTimeout(function(){
		largeDiv.style.opacity = 1;
	},0);
	
}
function cancelLarge(){
	var largeDiv = document.querySelector(".largeNum");
	largeDiv.style.opacity = 0;
	setTimeout(function(){
		largeDiv.style.display = "none";
		document.querySelector(".largeContent input").value = "";
	},950)

}

function submitPhoneNum(){
	var phone = document.querySelector(".largeContent input").value;
	var phoneReg = /^1[0-9]{10}$/;
	if(phoneReg.test(phone)){
//		向服务器发送匹配手机号的请求
		loadXMLDoc("POST","/game_server/box_package/invite_reward/",function(data){
			var back = JSON.parse(data);
			if(back.ok == true){
				boxMessage.biggest = back.biggest_envelope_position;
				var maxNumDiv = document.querySelector("#maxNumLight");
				var boxCell = document.querySelectorAll(".boxCell");
				var maxDiv = boxCell[(boxMessage.biggest.seq-1)];
				var boxAllIn = document.querySelector(".boxAllIn");
				maxNumDiv.style.left = (maxDiv.offsetLeft - boxAllIn.offsetLeft + window.innerWidth * 0.02075) + "px";
				maxNumDiv.style.top = (maxDiv.offsetTop - boxAllIn.offsetTop + window.innerWidth * 0.02075)+"px";
				setTimeout(function(){
					maxNumDiv.style.display = "block";
					var _index = boxMessage.biggest.section-1;
					var _t = parseInt(_index / 3);
					var _l = parseInt(_index % 3);
					scrolltopanimate((_t * window.innerWidth * 0.95), (_l * window.innerWidth * 0.95))
					cancelLarge();
				},0)
			}else if(back.error == "no_such_user") {
//				occMessage("没有找到这个手机号对应的用户。")
				document.querySelector(".submitType1").style.display = "none";
				document.querySelector(".largeerrortip").innerHTML = "没有找到这个手机号对应的用户";
				document.querySelector(".submitType2").style.display = "block";
			}else if(back.error == "too_late"){
//				occMessage("该手机号的用户注册已经超过两个小时了。")
				document.querySelector(".submitType1").style.display = "none";
				document.querySelector(".largeerrortip").innerHTML = "该手机号的用户注册已经超过两个小时了";
				document.querySelector(".submitType2").style.display = "block";
			}else if(back.error == "Invitee_has_not_play_br"){
//				occMessage("被邀请人还没有来玩过br红包")
				document.querySelector(".submitType1").style.display = "none";
				document.querySelector(".largeerrortip").innerHTML = "被邀请人还没有来玩过br红包";
				document.querySelector(".submitType2").style.display = "block";
			}else if(back.error == "Invitee_has_already_been_invited"){
//				occMessage("被邀请人已经被邀请过，邀请人已经领过奖励了。");
				document.querySelector(".submitType1").style.display = "none";
				document.querySelector(".largeerrortip").innerHTML = "被邀请人已经被邀请过，邀请人已经领过奖励了";
				document.querySelector(".submitType2").style.display = "block";
			}else if(back.error == "no_envelope"){
//				occMessage("没有红包");
				document.querySelector(".submitType1").style.display = "none";
				document.querySelector(".largeerrortip").innerHTML = "没有红包";
				document.querySelector(".submitType2").style.display = "block";
			}
		},{
			mobile:phone
		})
	}else{
		occMessage("请输入正确格式的手机号");
	}
	
}

function receivecard(str,url){
	var getCardShadowDiv = document.querySelector(".getCardShadow");
	setTimeout(function(){
		getCardShadowDiv.style.display = "block";
		getCardShadowDiv.style.opacity = 1;
	},0);
	var getCardDiv = document.createElement("div");
	getCardDiv.className = "getCard";
	getCardDiv.innerHTML = '<div class="getCardTitle">'+str+'送来一张祝福卡！</div><div class="card_content" style="background-image:url('+url+')"></div>';
	var click = document.createElement("div");
	click.className = "getcontent";
	click.innerHTML = "好的";
	click.onclick = function(){
		getCardDiv.className = "getCard appearport";
		setTimeout(function(){
			getCardDiv.style.display = "none";
			getCardShadowDiv.removeChild(getCardDiv);
			setTimeout(function(){ 
				if(getCardShadowDiv.innerHTML.length == 0){
					getCardShadowDiv.style.opacity = 0;
					setTimeout(function(){
						getCardShadowDiv.style.display = "none";
					},250)
				}
			},0)
		},250);
	}
	getCardDiv.appendChild(click);
	getCardShadowDiv.appendChild(getCardDiv);
	setTimeout(function(){
		getCardDiv.style.display = "block";
		getCardDiv.className = "getCard occport";
	},0)
}
function giveupmoney(){
	loadXMLDoc("POST","/game_server/box_package/draw_card/",function(data){
		var back = JSON.parse(data);
		if(back.ok == true){
			receivecard(back.op.sender_name,back.card.small_pict_url)
		}else {
			occMessage("领取福卡失败了。")
		}
	},{
		money:boxMessage.nowBox.money
	})
	cancelfindmoney();
}
