//初始化数据或从本地储存中取出数据
audio = document.createElement("audio");
allowWrite = 0;
sImg = new Image();
festivalCode = null;
fMon = 0;
fDay = 0;
mainImgCode = null;
// if (localStorage.getItem("clickCode")==null||localStorage.getItem("fallCode")==null||localStorage.getItem("musicCode")==null) {
// 	musicCode = 0;
// 	clickCode = 0;
// 	fallCode = 0;
// 	localStorage.setItem("musicCode",musicCode);
// 	localStorage.setItem("clickCode",clickCode);
// 	localStorage.setItem("fallCode",fallCode);
// } else {
// 	musicCode = localStorage.getItem("musicCode");
// 	clickCode = localStorage.getItem("clickCode");
// 	fallCode = localStorage.getItem("fallCode");
// }
if (localStorage.getItem("clickCode")==null) {
	clickCode = 0;
	localStorage.setItem("clickCode",clickCode);
} else {
	clickCode = localStorage.getItem("clickCode");
}
if (localStorage.getItem("fallCode")==null) {
	fallCode = 0;
	localStorage.setItem("fallCode",fallCode);
} else {
	fallCode = localStorage.getItem("fallCode");
}
if (localStorage.getItem("musicCode")==null) {
	musicCode = 0;
	localStorage.setItem("musicCode",musicCode);
} else {
	musicCode = localStorage.getItem("musicCode");
}

modelList = [
	{"show":"无","content":""},
	{"show":"...很重要","content":"#很重要"},
	{"show":"记得...","content":"记得#"},
	{"show":"有...","content":"有#"},
	{"show":"该...了","content":"该#了"},
	{"show":"...时间","content":"#时间"},
];
contentList = [
	{"show":"无","content":""},
	{"show":"游戏","content":"游戏"},
	{"show":"休息","content":"休息"},
	{"show":"看番","content":"看番"},
	{"show":"学习","content":"学习"},
	{"show":"工作","content":"工作"},
	{"show":"约会","content":"约会"},
	{"show":"见面","content":"见面"},
	{"show":"开会","content":"开会"},
	{"show":"吃饭","content":"吃饭"},
	{"show":"睡觉","content":"睡觉"},
];

MlistPos = 0;
ClistPos = 0;
inputPos = 0;
telinputPos = 0;

function MCtime() {
	this.MCyear = 2016;
	this.MCmonth = 1;
	this.MCday = 1;
	this.MChour = 0;
	this.MCminute = 0;
	this.MCsecond = 0;
}
MCtime = new MCtime();
// deadline = new Array(20);
// dayPlan = new Array(2);
function Deadline() {
	this.usedCode = 0;
	this.dayPlanDetail = null;
	this.dayPlanRough = null;
	this.Year = null;
	this.Month = null;
	this.Day = null;
	this.Hour = null;
	this.Minute = null;
	this.Second = null;
}

if(!(localStorage.getItem("moveLeft")==null||localStorage.getItem("moveTop")==null)) {
	moveLeft = localStorage.getItem("moveLeft");
	moveTop = localStorage.getItem("moveTop");
} else {
	console.log("xyNULL");
	moveTop = null;
	moveLeft = null;
}
if (localStorage.getItem("remindCode")==null) {
	remindCode = 1;
	localStorage.setItem("remindCode",remindCode);
} else {
	remindCode = localStorage.getItem("remindCode");
}
if (localStorage.getItem("posLockCode")==null) {
	posLockCode = 0;
	localStorage.setItem("posLockCode",posLockCode);
} else {
	posLockCode = localStorage.getItem("posLockCode");
}
console.log("remindCode:"+remindCode);
if (localStorage.getItem("mainImgCode")==null) {
	mainImgCode = "img0";
	localStorage.setItem("mainImgCode",mainImgCode);
} else {
	mainImgCode = localStorage.getItem("mainImgCode");
}
if (localStorage.getItem("backgroundCode")==null) {
	backgroundCode = "bg";
	localStorage.setItem("backgroundCode",backgroundCode);
} else {
	backgroundCode = localStorage.getItem("backgroundCode");
}
if (localStorage.getItem("colorStyleCode")==null) {
	colorStyleCode = "black";
	localStorage.setItem("colorStyleCode",colorStyleCode);
} else {
	colorStyleCode = localStorage.getItem("colorStyleCode");
}
if (localStorage.getItem("festivalCode")==null) {
	festivalCode = true;
} else {
	festivalCode = localStorage.getItem("festivalCode");
}
if (localStorage.getItem("DeadLineArray")==null||localStorage.getItem("DeadLineArray")=="") {
	//定义一个长度为20的Deadline数组
	DeadLineArray = new Array(20);
	for (var i = 0; i < DeadLineArray.length; i++) {
		DeadLineArray[i] = new Deadline();
	}
	// console.log(JSON.stringify(DeadLineArray));
} else {
	DeadLineArray = eval(localStorage.getItem("DeadLineArray"));
}
//到达deadline时间时，deadline前移
function DeadlinePOP() {
	for (var i = 0; i < DeadLineArray.length-1; i++) {
		DeadLineArray[i] = $.parseJSON(JSON.stringify(DeadLineArray[i+1]));
	}
	if (DeadLineArray[19].usedCode == 1) {
		DeadLineArray[19] = new Deadline();
	}
	console.log("pop:"+JSON.stringify(DeadLineArray));
	localStorage.setItem("DeadLineArray",JSON.stringify(DeadLineArray));
	writeDeadline();
}
//比较CompareItem的时间与各时间参数组成的时间，如果CompareItem与之相等，return "EQ"
//                                             如果CompareItem较小，reurn "LT"
//											   如果CompareItem较大，reurn "GT"
function DeadlineCompare(year,month,day,hour,minute,second,CompareItem) {
	year = parseInt(year);
	month = parseInt(month);
	day = parseInt(day);
	hour = parseInt(hour);
	minute = parseInt(minute);
	second = parseInt(second);

	var COMyear = parseInt(CompareItem.Year);
	var COMmonth = parseInt(CompareItem.Month);
	var COMday = parseInt(CompareItem.Day);
	var COMhour = parseInt(CompareItem.Hour);
	var COMminute = parseInt(CompareItem.Minute);
	var COMsecond = parseInt(CompareItem.Second); 

	console.log(year+"-"+month+"-"+day+" "+hour+":"+minute+":"+second+"\n"
		+COMyear+"-"+COMmonth+"-"+COMday+" "+COMhour+":"+COMminute+":"+COMsecond);

	if (COMyear == year) {
		if (COMmonth == month) {
			if (COMday == day) {
				if (COMhour == hour) {
					if (COMminute == minute) {
						if (COMsecond== second) {
							console.log("CompareItem:EQ");
							return "EQ";
						} else if (COMsecond< second) {
							console.log("CompareItem:secondLT");
							return "LT";
						} else if (COMsecond> second) {
							console.log("CompareItem:secondGT");
							return "GT";
						}
					} else if (COMminute < minute) {
						console.log("CompareItem:minuteLT");
						return "LT";
					} else if (COMminute > minute) {
						console.log("CompareItem:minuteGT");
						return "GT";
					}
				} else if (COMhour < hour) {
					console.log("CompareItem:hourLT");
					return "LT";
				} else if (COMhour > hour) {
					console.log("CompareItem:hourGT");
					return "GT";
				}
			} else if (COMday < day) {
				console.log("CompareItem:dayLT");
				return "LT";
			} else if (COMday > day) {
				console.log("CompareItem:dayGT");
				return "GT";
			}
		} else if (COMmonth < month) {
			console.log("CompareItem:monthLT");
			return "LT";
		} else if (COMmonth > month) {
			console.log("CompareItem:monthGT");
			return "GT";
		}
	} else if (COMyear < year) {
		console.log("CompareItem:yearLT");
		return "LT";
	} else if (COMyear > year) {
		console.log("CompareItem:yearGT");
		return "GT";
	} else {
		console.log("CompareItem:EM");
		return "EM";
	}
}
//根据用户在闹钟填入的信息，生成对应的Deadline节点
function DeadlineINPUT(detail,rough,year,month,day,hour,minute,second) {
	console.log("inputData:"+year+"-"+month+"-"+day+" "+hour+":"+minute+":"+second);
	if (DeadLineArray[19].usedCode == 0) {
		for (var i = 10; i < DeadLineArray.length; i++) {
			console.log("for[i]:"+i);
			console.log("result:"+DeadlineCompare(year,month,day,hour,minute,second,DeadLineArray[i]));
			if (DeadlineCompare(year,month,day,hour,minute,second,DeadLineArray[i]) == "EQ") {
				//输出存在相同的闹钟时间，错误
				break;
			} else if (DeadlineCompare(year,month,day,hour,minute,second,DeadLineArray[i]) == "GT") {
				for (var j = DeadLineArray.length - 1; j >= i+1; j--) {
					console.log("i:"+i+"|j:"+j);
					DeadLineArray[j] = $.parseJSON(JSON.stringify(DeadLineArray[j-1]));
				}
				console.log(JSON.stringify(DeadLineArray));
				DeadLineArray[i].usedCode = 1;
				DeadLineArray[i].dayPlanDetail = detail;
				DeadLineArray[i].dayPlanRough = rough;
				DeadLineArray[i].Year = year;
				DeadLineArray[i].Month = month;
				DeadLineArray[i].Day = day;
				DeadLineArray[i].Hour = hour;
				DeadLineArray[i].Minute = minute;
				DeadLineArray[i].Second = second;
				console.log("("+i+")gt:"+JSON.stringify(DeadLineArray));
				localStorage.setItem("DeadLineArray",JSON.stringify(DeadLineArray));
				break;
			}
			if (DeadLineArray[i].usedCode == 0) {
				console.log("i:"+i);
				DeadLineArray[i].usedCode = 1;
				DeadLineArray[i].dayPlanDetail = detail;
				DeadLineArray[i].dayPlanRough = rough;
				DeadLineArray[i].Year = year;
				DeadLineArray[i].Month = month;
				DeadLineArray[i].Day = day;
				DeadLineArray[i].Hour = hour;
				DeadLineArray[i].Minute = minute;
				DeadLineArray[i].Second = second;
				console.log(JSON.stringify(DeadLineArray));
				localStorage.setItem("DeadLineArray",JSON.stringify(DeadLineArray));
				break;
			}
		}
	} else {
		//输出时间表已满，请有剩余空间时再添加
	}
}
//删除deadline节点
function DeadlineDelete(pos) {
	for (var i = pos; i < DeadLineArray.length-1; i++) {
		DeadLineArray[i] = $.parseJSON(JSON.stringify(DeadLineArray[i+1]));
	}
	if (DeadLineArray[19].usedCode == 1) {
		DeadLineArray[19] = new Deadline();
	}
	// console.log("delete["+pos+"]:"+JSON.stringify(DeadLineArray));
	localStorage.setItem("DeadLineArray",JSON.stringify(DeadLineArray));
	writeDeadline();
}
//闹钟
function deadlineRemind(y,mon,d,h,m,s) {
	var arr = DeadLineArray[10];
	if (remindCode == 1) {
		if (DeadlineCompare(y,mon,d,h,m,s,arr) == "EQ") {
			$("#deadlineModal").modal('hide');
			$("#settingModal").modal('hide');
			if (arr.dayPlanDetail == "") {
				$("#modalRemind").html("您有事件安排，请注意时间");
			} else {
				$("#modalRemind").html(arr.dayPlanDetail);
			}
			$('#clickModal').modal('show');
			$(".musicControl").css("display","block");
			audio.pause();
			if('fastSeek' in audio){
				audio.fastSeek(0);
			} else {
				audio.currentTime = 0;
			}
			chooseMusic();
			audio.play();
		} else if (DeadlineCompare(y,mon,d,h,m,s,arr) == "LT") {
			console.log("LT");
			DeadlinePOP();
		} else if (DeadlineCompare(y,mon,d,h,m,s,arr) == "EM") {
			DeadlineDelete(10);
		}
	} else if (arr.usedCode == 1) {
		if (DeadlineCompare(y,mon,d,h,m,s,arr) == "LT") {
			console.log("LT");
			DeadlinePOP();
		}
	} 
}
//根据musicCode选择audio的url
function chooseMusic() {
	console.log("musicCode(choose):"+musicCode);
	var musicUrl = null;
	if (musicCode==0) {
		musicUrl = "GodKnows";
	} else if (musicCode==1) {
		musicUrl = "YasashiiBoukyaku";
	} else if (musicCode==2) {
		musicUrl = "Boukendeshodesho";
	}
	if (audio.canPlayType("audio/mp3")) {
	    audio.src = "audio/"+musicUrl+".mp3";
	}else if(audio.canPlayType("audio/ogg")) {
	    audio.src = "audio/"+musicUrl+".ogg";
	}else if(audio.canPlayType("audio/m4a")) {
	    audio.src = "audio/"+musicUrl+".m4a";
	}
}
//变换背景
function switchBG() {
	$("body").css({
		"background":"url(img/"+backgroundCode+".jpg)",
		"background-size":"cover",
		"-webkit-background-size":"cover",
		"-moz-background-size":"cover"
	});
	if (colorStyleCode == "black") {
		$(".time").css("color","rgba(0,0,0,0.5)");
		$(".upORdown").css("color","rgba(0,0,0,0.5)");
		$(".settingBtn").css("color","rgba(0,0,0,0.5)");
	} else if (colorStyleCode == "white") {
		console.log("white");
		$(".time").css("color","#fff");
		$(".upORdown").css("color","#fff");
		$(".settingBtn").css("color","#fff");
	}
}
//变换主题
function switchTYPE() {
	if (colorStyleCode == "black") {
		$(".time").css("color","rgba(0,0,0,0.5)");
		$(".upORdown").css("color","rgba(0,0,0,0.5)");
		$(".settingBtn").css("color","rgba(0,0,0,0.5)");
	} else if (colorStyleCode == "white") {
		console.log("white");
		$(".time").css("color","#fff");
		$(".upORdown").css("color","#fff");
		$(".settingBtn").css("color","#fff");
	}
}
//将一位整数变为“01”的形式
function addZero(num) {
	return num<10?'0'+num:num;
}
function week(num) {
	switch(num) {
		case 0:return "Sun."; break;
		case 1:return "Mon."; break;
		case 2:return "Tues."; break;
		case 3:return "Wed."; break;
		case 4:return "Thur."; break;
		case 5:return "Fri."; break;
		case 6:return "Sat"; break;
	}
}
//给下拉菜单从num1到num2的整数选项
function AddLi(classSTR,th,num1,num2) {
	for (var i = num1; i <= num2; i++) {
		var _in = th.find("ul").html();
		th.find("ul").html(_in+"<li><a class='"+classSTR+"'>"+i+"</a></li>");
	}
}
//sideBar的主要函数
function sideBar(){
	var SystemDate = new Date();
	//时间
	var h = SystemDate.getHours();
	var m = SystemDate.getMinutes();
	var s = SystemDate.getSeconds();
	var time = addZero(h)+":"+addZero(m)+":"+addZero(s);
	$(".time").html(time);		
	//日期
	var y = SystemDate.getFullYear();
	var mon = SystemDate.getMonth()+1;
	var d = SystemDate.getDate();
	var w = SystemDate.getDay();
	var date = addZero(y)+"-"+addZero(mon)+"-"+addZero(d)+"&nbsp;&nbsp;"+week(w);
	$(".date").html(date);

	// $("#clickHour").html(addZero(h));
	// $("#clickMinute").html(addZero(m));
	// $("#clickSecond").html(addZero(s));
	// $("#clickYear").html(y);
	// $("#clickMonth").html(addZero(mon));
	// $("#clickDay").html(addZero(d));
	fMon = mon;
	fDay = d;
	
	//click
	var clickY = localStorage.getItem("Year")?localStorage.getItem("Year"):0;
	var clickMon = localStorage.getItem("Month")?clickMon = localStorage.getItem("Month"):0;
	var clickD = localStorage.getItem("Day")?localStorage.getItem("Day"):0;
	var clickH = localStorage.getItem("Hour")?localStorage.getItem("Hour"):0;
	var clickM = localStorage.getItem("Minute")?localStorage.getItem("Minute"):0;
	var clickS = localStorage.getItem("Second")?localStorage.getItem("Second"):0;
	$("#clickYear").html(addZero(clickY));
	$("#clickMonth").html(addZero(clickMon));
	$("#clickDay").html(addZero(clickD));
	$("#clickHour").html(addZero(clickH));
	$("#clickMinute").html(addZero(clickM));
	$("#clickSecond").html(addZero(clickS));

	deadlineRemind(y,mon,d,h,m,s);
	if (clickCode==1) {//控制闹钟的伸缩
		$(".click").slideDown();
		$(".clickBtn").find("span").removeClass("glyphicon glyphicon-chevron-down");
		$(".clickBtn").find("span").addClass("glyphicon glyphicon-chevron-up");
		// if ($("#clickYear").html()==y&&
		// 	$("#clickMonth").html()==mon&&
		// 	$("#clickDay").html()==d&&
		// 	$("#clickHour").html()==h&&
		// 	$("#clickMinute").html()==m&&
		// 	$("#clickSecond").html()==s) {
		// 	$('#clickModal').modal('show');
		// 	audio.pause();
		// 	if('fastSeek' in audio){
		// 		audio.fastSeek(currentTime);
		// 	} else {
		// 		audio.currentTime = 0;
		// 	}
		// 	audio.play();
		// }
	}
}
$(".addDeadline").click(function(){
	var rough = $("#roughInput").val();
	var detail = $("#detailInput").val();
	var clickY = localStorage.getItem("Year")?localStorage.getItem("Year"):0;
	var clickMon = localStorage.getItem("Month")?clickMon = localStorage.getItem("Month"):0;
	var clickD = localStorage.getItem("Day")?localStorage.getItem("Day"):0;
	var clickH = localStorage.getItem("Hour")?localStorage.getItem("Hour"):0;
	var clickM = localStorage.getItem("Minute")?localStorage.getItem("Minute"):0;
	var clickS = localStorage.getItem("Second")?localStorage.getItem("Second"):0;
	DeadlineINPUT(detail,rough,clickY,clickMon,clickD,clickH,clickM,clickS);
	writeDeadline();
});
//控制.main内的图像水平居中
function imgPos(w){
	var mainIMG = $(".main").children();
	// var imgW = mainIMG.width();
	mainIMG.css("left",-w/2+'px');
	console.log("imgW:"+w);
}
//控制星星飘过
function Star() {
	var srcN = Math.floor(Math.random()*3+1);
	var star = $("<img></img>").attr("src","img/"+srcN+".png");
	_top = Math.random()*($(document).height()-150);
	//z-index
	var z = [1,3];
	var num = Math.floor(Math.random()*2);
	var zIndex = z[num];
	//width
	var wList = [50,60,80,100,130];
	var num2 = Math.floor(Math.random()*5);
	var _width = wList[num2];
	//rotate
	var _rotate = Math.floor(Math.random()*360);
	//speed
	var spList = [4000,5000,8000,10000];
	var num3 = Math.floor(Math.random()*4);
	var _speed = spList[num3];
	//
	// console.log(zIndex+"("+num+")|"+_width+"("+num2+")|"+_rotate+"|"+_speed+"("+num3+")");
	star.css({"position":"fixed","top":_top,"left":-150,"z-index":zIndex,"width":_width,"transform":"rotate("+_rotate+"deg)"});
	$("body").append(star);
	// console.log(star.css("transform"));
	star.animate({
		left:$(document).width(),
		opacity:0,
	},{
		duration:_speed,
		step: function(now,fx){
			_rotate+=0.4;
			star.css("transform","rotate("+_rotate+"deg)");
		},
		complete: function(){
			star.remove();
		}
	});
}
//控制樱花的飘落
function flower() {
	var flower = $("<img></img>").attr("src","img/flower.png");
	_top = Math.random()*($(document).height()-150);
	_left = Math.random()*($(document).width());
	//z-index
	var z = [1,3];
	var num = Math.floor(Math.random()*2);
	var zIndex = z[num];
	//rotate
	var _rotate = Math.floor(Math.random()*360);
	//speed
	var spList = [4000,5000,8000,10000];
	var num3 = Math.floor(Math.random()*4);
	var _speed = spList[num3];
	//
	if(Math.random()>0.5){
		flower.css({"position":"fixed","top":_top,"left":-150,"z-index":zIndex,"width":20,"transform":"rotate("+_rotate+"deg)"});
	} else {
		flower.css({"position":"fixed","top":-100,"left":_left,"z-index":zIndex,"width":20,"transform":"rotate("+_rotate+"deg)"});
	}
	$("body").append(flower);
	// console.log(flower.css("transform"));
	flower.animate({
		left:$(document).width()+300,
		top: $(document).height()+300,
		opacity:0,
	},{
		duration:_speed,
		step: function(now,fx){
			_rotate+=0.4;
			flower.css("transform","rotate("+_rotate+"deg)");
		},
		complete: function(){
			flower.remove();
		}
	},function(){flower.remove();});
}
//使tx可以用鼠标拖拽
function move(tx) {
	var isDown = false;
	$(tx).mousedown(function(event) {
		if (posLockCode == 1) {return}
		var event = event || window.event;
		mX = event.clientX;
		mY = event.clientY;
		dX = $(tx).offset().left;
		dY = $(tx).offset().top;
		isDown = true;//鼠标拖拽启动
	});
	$(document).mousemove(function(event) {
		if (posLockCode == 1) {return}
		var event = event || window.event;
		var x = event.clientX;//鼠标滑动时的X轴
		var y = event.clientY;//鼠标滑动时的Y轴
		if(isDown) {
			moveLeft = x - mX + dX;
			moveTop = y - mY + dY;
			localStorage.setItem("moveLeft",moveLeft);
			localStorage.setItem("moveTop",moveTop);
			$(tx).css({"left": moveLeft,"top": moveTop});//div动态位置赋值
		}
	});
	$(tx).mouseup(function() {
		if (posLockCode == 1) {return}
		isDown = false;//鼠标拖拽结束
		console.log("x:"+localStorage.getItem("moveLeft")+"|y:"+localStorage.getItem("moveTop"));
	});	
}
//控制闹钟伸缩
$(".clickBtn").click(function(){
	$(".click").slideToggle();
	$(this).find("span").toggleClass("glyphicon glyphicon-chevron-up");
	$(this).find("span").toggleClass("glyphicon glyphicon-chevron-down");
	if (clickCode==0) {clickCode=1;localStorage.setItem("clickCode",clickCode);}
	else if (clickCode==1) {
		clickCode=0;
		localStorage.setItem("clickCode",clickCode);
		// audio.pause();
		// if('fastSeek' in audio){
		// 	audio.fastSeek(currentTime);
		// } else {
		// 	audio.currentTime = 0;
		// }
	}
	console.log("clickCode:"+clickCode);
});
//控制deadline伸缩
$(".deadlineBtn").click(function(){
	$(".deadline").slideToggle();
	$(this).find("span").toggleClass("glyphicon glyphicon-chevron-up");
	$(this).find("span").toggleClass("glyphicon glyphicon-chevron-down");
});
//填充deadline
function writeDeadline() {
	console.log("OK");
	var Node = $(".deadlineNode");
	console.log(Node.length);
	for (var i = 0,j = 8; i < Node.length; i++,j++) {
		var arr = DeadLineArray[j];
		if(arr.usedCode == 0){
			Node.eq(i).find(".noteP").html("");
			Node.eq(i).find(".timeP").html("");
			continue;
		} else {
			var year = arr.Year;
			var month = arr.Month;
			var day = arr.Day;
			var hour = arr.Hour;
			var minute = arr.Minute;
			var second = arr.Second;
			var time = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
			Node.eq(i).find(".noteP").html(DeadLineArray[j].dayPlanRough);
			Node.eq(i).find(".timeP").html(time);
		}
	}
	if($("#deadlineModal").attr("aria-hidden") != "false" || $("#deadlineEmpty").is(":focus") || allowWrite) {
		console.log("aria-hidden:"+$("#deadlineModal").attr("aria-hidden"));
		var detailNode = $(".deadlineDetailNode");
		for (var k = 10; k < DeadLineArray.length; k++) {
			var num = k-10;
			var arr = DeadLineArray[k];

			var detail = arr.dayPlanDetail;
			var rough = arr.dayPlanRough;
			var year = arr.Year;
			var month = arr.Month;
			var day = arr.Day;
			var hour = arr.Hour;
			var minute = arr.Minute;
			var second = arr.Second;

			detailNode.eq(num).find("input[name='detailDetail']").val(detail);
			detailNode.eq(num).find("input[name='detailRough']").val(rough);
			detailNode.eq(num).find("input[name='detailyear']").val(year);
			detailNode.eq(num).find("input[name='detailmonth']").val(month);
			detailNode.eq(num).find("input[name='detailday']").val(day);
			detailNode.eq(num).find("input[name='detailhour']").val(hour);
			detailNode.eq(num).find("input[name='detailminute']").val(minute);
			detailNode.eq(num).find("input[name='detailsecond']").val(second);

			console.log("detailWrite OK");
		}
	}
}
//填充模板选择框
function WriteModel() {
	var Mth = $("[type=infModelList]");
	for (var i = 0; i < modelList.length; i++) {
		var Model_in = modelList[i].show;
		console.log("arr[i].show:"+Model_in);
		Mth.append("<li><a class='clickModel'>"+Model_in+"</a></li>");
	}

	var Mth = $("[type=infContentList]");
	for (var i = 0; i < contentList.length; i++) {
		var Content_in = contentList[i].show;
		console.log("arr[i].show:"+Content_in);
		Mth.append("<li><a class='clickContent'>"+Content_in+"</a></li>");
	}

}
//控制设置窗口显示
$(".settingBtn").click(function(){
	$('#settingModal').modal('show');
});
//deadLine窗口的显示
$(".deadlineDetailBtn").click(function(){
	$('#deadlineModal').modal('show');
});
//使按钮能控制飘落物切换
$(".FallSwitchBtn").each(function(){
	$(this).click(function(){
		var c = $(this).val();
		fallCode = c;
		localStorage.setItem("fallCode",fallCode);
		$(".FallSwitchBtn").removeClass("btn-primary");
		$(".FallSwitchBtn").addClass("btn-default");
		$(".FallSwitchBtn").removeAttr("disabled");
		$(this).attr("disabled","disabled");
		$(this).toggleClass("btn-default");
		$(this).toggleClass("btn-primary");
		console.log(fallCode);
		Fall();
	});
});
//使按钮能控制闹钟音乐的切换
$(".MusicSwitchBtn").each(function(){
	$(this).click(function(){
		var mc = $(this).val();
		musicCode = mc;
		localStorage.setItem("musicCode",musicCode);
		$(".MusicSwitchBtn").removeClass("btn-primary");
		$(".MusicSwitchBtn").addClass("btn-default");
		$(".MusicSwitchBtn").removeAttr("disabled");
		$(this).attr("disabled","disabled");
		$(this).toggleClass("btn-default");
		$(this).toggleClass("btn-primary");
		console.log(musicCode);
		// chooseMusic();
	});
});
//使按钮能控制人物图像的切换
$(".imgSwitchBtn").each(function(){
	$(this).click(function(){
		var ic = $(this).val();
		mainImgCode = ic;
		festivalCode = false;
		localStorage.setItem("festivalCode",festivalCode);
		localStorage.setItem("mainImgCode",mainImgCode);
		$(".imgSwitchBtn").removeClass("btn-primary");
		$(".imgSwitchBtn").addClass("btn-default");
		$(".imgSwitchBtn").removeAttr("disabled");
		$(this).attr("disabled","disabled");
		$(this).toggleClass("btn-default");
		$(this).toggleClass("btn-primary");
		console.log(mainImgCode);
		switchIMG();
	});
});
//使按钮能控制背景的切换
$(".BGswitchBtn").each(function(){
	$(this).click(function(){
		var bgc = $(this).val();
		var csc = $(this).attr("colorStyle");
		backgroundCode = bgc;
		localStorage.setItem("backgroundCode",backgroundCode);
		$(".BGswitchBtn").removeClass("btn-primary");
		$(".BGswitchBtn").addClass("btn-default");
		$(".BGswitchBtn").removeAttr("disabled");
		$(this).attr("disabled","disabled");
		$(this).toggleClass("btn-default");
		$(this).toggleClass("btn-primary");
		switchBG();
	});
});
//使按钮能控制主题的切换
$(".TYPEswitchBtn").each(function(){
	$(this).click(function(){
		var csc = $(this).attr("colorStyle");
		colorStyleCode = csc;
		localStorage.setItem("colorStyleCode",colorStyleCode);
		$(".TYPEswitchBtn").removeClass("btn-primary");
		$(".TYPEswitchBtn").addClass("btn-default");
		$(".TYPEswitchBtn").removeAttr("disabled");
		$(this).attr("disabled","disabled");
		$(this).toggleClass("btn-default");
		$(this).toggleClass("btn-primary");
		switchTYPE();
	});
});
// 控制闹钟提醒的开关
$('#remindSwitch').on({
    'switchChange.bootstrapSwitch': function(event, state) {
    	if ($("#remindSwitch").is(":focus") == true) {
    		if (remindCode == 1) {
    			$("#remindSwitch").blur();
    			remindCode = 0;
    		} else {
    			$("#remindSwitch").blur();
    			remindCode = 1;
    		}
    		console.log(remindCode);
    		localStorage.setItem("remindCode",remindCode);
    	} 
    }
});
$('#posLockSwitch').on({
    'switchChange.bootstrapSwitch': function(event, state) {
    	if ($("#posLockSwitch").is(":focus") == true) {
    		if (posLockCode == 1) {
    			$("#posLockSwitch").blur();
    			posLockCode = 0;
    		} else {
    			$("#posLockSwitch").blur();
    			posLockCode = 1;
    		}
    		console.log(posLockCode);
    		localStorage.setItem("posLockCode",posLockCode);
    	} 
    }
});
// 控制飘落物的切换
var f1=null;
var f2=null;
function Fall() {
	if (fallCode==0) {
		f1 = setInterval("Star()",500);
		clearInterval(f2);
	}
	else if (fallCode==1) {
		f2 = setInterval("flower()",100);
		clearInterval(f1);
	}
}

function IntervalIMG() {
	var img = $(".main").children();
	imgPos();
}
//控制人物图像的自动切换
function switchIMG() {
	console.log("festivalCode",festivalCode);
	if (festivalCode==true) {
		console.log("fMon:"+fMon+"|fDay:"+fDay);
		if (fMon==12&&fDay==25) {
			sImg.src = "img/suzumiyaChristmas.png";
			mainImgCode = "suzumiyaChristmas";
		} else {
			sImg.src = "img/"+mainImgCode+".png";
		}
	} else {
		sImg.src = "img/"+mainImgCode+".png";
	}
	$(".main").append(sImg);
	sImg.onload=function(){
		var w = sImg.width;
		var winH = $(document).height();
		if (mainImgCode == "suzumiyaChristmas") {
			var h = sImg.height;
			$(".main").css("top",winH - h + 'px');
		} else {
			$(".main").css({"left":moveLeft+'px',"top":moveTop+'px'});
		}
		imgPos(w);
	};    
	
}
//控制人物位置复位
$("#resetBtn").click(function() {
	localStorage.setItem("moveLeft",null);
	localStorage.setItem("moveTop",null);
	$(".main").css({"left":"50%","top":"5%"});

})
//清空deadline
$("#deadlineEmpty").click(function(){
	DeadLineArray = new Array(20);
	for (var i = 0; i < DeadLineArray.length; i++) {
		DeadLineArray[i] = new Deadline();
	}
	localStorage.setItem("DeadLineArray","");
	console.log(JSON.stringify(DeadLineArray));
	allowWrite = 1;
	writeDeadline();
	allowWrite = 0;
})
//保存deadline更改
$("#deadlineSave").click(function(){
	var detailNode = $(".deadlineDetailNode");
	for (var k = 10; k < DeadLineArray.length; k++) {
		var num = k-10;
		var arr = DeadLineArray[k];
		DeadLineArray[k].dayPlanDetail= detailNode.eq(num).find("input[name='detailDetail']").val();
		DeadLineArray[k].dayPlanRough= detailNode.eq(num).find("input[name='detailRough']").val();
		DeadLineArray[k].Year= detailNode.eq(num).find("input[name='detailyear']").val();
		DeadLineArray[k].Month= detailNode.eq(num).find("input[name='detailmonth']").val();
		DeadLineArray[k].Day= detailNode.eq(num).find("input[name='detailday']").val();
		DeadLineArray[k].Hour= detailNode.eq(num).find("input[name='detailhour']").val();
		DeadLineArray[k].Minute= detailNode.eq(num).find("input[name='detailminute']").val();
		DeadLineArray[k].Second= detailNode.eq(num).find("input[name='detailsecond']").val();

		if(DeadLineArray[k].Year&&DeadLineArray[k].Month&&DeadLineArray[k].Day&&
			DeadLineArray[k].Hour&&DeadLineArray[k].Minute&&DeadLineArray[k].Second){
			DeadLineArray[k].usedCode = 1;
		}

		console.log("detailSave OK");
	}
	console.log(JSON.stringify(DeadLineArray));
	localStorage.setItem("DeadLineArray",JSON.stringify(DeadLineArray));
	writeDeadline();
})
//确认讯息的写入
$("#inputConfirm").click(function () {
	$("input").eq(inputPos).val(modelReplace(modelList[MlistPos].content,'#',contentList[ClistPos].content));
});
$("#inputTime").click(function () {
	var posCeil = Math.ceil((telinputPos+1)/6)-1;
	console.log("posceil:"+posCeil);
	$("[name=detailyear]").eq(posCeil).val(MCtime.MCyear);
	$("[name=detailmonth]").eq(posCeil).val(MCtime.MCmonth);
	$("[name=detailday]").eq(posCeil).val(MCtime.MCday);
	$("[name=detailhour]").eq(posCeil).val(MCtime.MChour);
	$("[name=detailminute]").eq(posCeil).val(MCtime.MCminute);
	$("[name=detailsecond]").eq(posCeil).val(MCtime.MCsecond);
});
//musicControl的点击事件
$("#musicStop").click(function(){
	$(".musicControl").css("display","none");
	audio.pause();
	if('fastSeek' in audio){
		audio.fastSeek(0);
	} else {
		audio.currentTime = 0;
	}
})
$("#musicPause").click(function(){
	audio.pause();
})
$("#musicPlay").click(function(){
	audio.play();
})
//在deadline模拟态中加入各节点视图
function addDeadlineDetailNode() {
	var content = "";
	for (var i = 1; i <= 10; i++) {
		var addClass = "";
		if (i==1) {addClass = "next"}
		content += "<div class='deadlineDetailNode "+addClass+"' turn = '"+i+"'>\
						<input type='text' name='detailRough' class='deadlineText'>\
						<input type='text' name='detailDetail' class='deadlineText'>\
						<input type='tel' name='detailyear' class='deadlineNum'>\
						<input type='tel' name='detailmonth' class='deadlineNum'>\
						<input type='tel' name='detailday' class='deadlineNum'>\
						<input type='tel' name='detailhour' class='deadlineNum'>\
						<input type='tel' name='detailminute' class='deadlineNum'>\
						<input type='tel' name='detailsecond' class='deadlineNum'>\
						<span class='glyphicon glyphicon-remove PlanDelete'></span>\
    				</div>"
    	$(".deadlineModalBody").html(content);
	}
}
//替换
function modelReplace(str,c1,c2) {
	return str.replace(c1,c2);
}
//生成预览
function previewTime() {
	if(MCtime.MCyear!=""&&MCtime.MCmonth!=""&&MCtime.MCday!=""&&MCtime.MChour!=""&&MCtime.MCminute!=""&&MCtime.MCsecond!=""){
		return MCtime.MCyear+"-"+MCtime.MCmonth+"-"+MCtime.MCday+" "+MCtime.MChour+":"+MCtime.MCminute+":"+MCtime.MCsecond;
	}
	else return "";
}
function previewWrite(str) {
	$(".preview").html(str);
}
$(document).ready(function(){
	console.log("remindCode:"+remindCode);
	if (posLockCode == 1) {
		$("#posLockSwitch").bootstrapSwitch("state", true);
	} else {
		$("#posLockSwitch").bootstrapSwitch("state", false);
	}
	if (remindCode == 1) {
		$("#remindSwitch").bootstrapSwitch("state", true);
	} else {
		$("#remindSwitch").bootstrapSwitch("state", false);
	}
	addDeadlineDetailNode();
	writeDeadline();
	move(".main");
	// move(".sideBar");
	// chooseMusic();
	// sideBar();
	// switchBG();
	console.log("ox:"+moveLeft+"|oy:"+moveTop);
	$(".main").css({"left":moveLeft+'px',"top":moveTop+'px'});
	console.log("mx:"+ $(".main").css("left")+"|my:"+ $(".main").css("top"));
	setInterval("sideBar()",1000);
	Fall();
	switchIMG();
	switchBG();
	imgPos();
	console.log(JSON.stringify(DeadLineArray));
	AddLi("clickNum",$(".Year"),2016,2020);
	AddLi("clickNum",$(".Month"),1,12);
	AddLi("clickNum",$(".Day"),1,31);
	AddLi("clickNum",$(".Hour"),0,23);
	AddLi("clickNum",$(".Minute"),0,59);
	AddLi("clickNum",$(".Second"),0,59);

	AddLi("changeClickNum",$(".changeYear"),2016,2020);
	AddLi("changeClickNum",$(".changeMonth"),1,12);
	AddLi("changeClickNum",$(".changeDay"),1,31);
	AddLi("changeClickNum",$(".changeHour"),0,23);
	AddLi("changeClickNum",$(".changeMinute"),0,59);
	AddLi("changeClickNum",$(".changeSecond"),0,59);

	WriteModel();

	//讯息窗口的显示和Input操作
	$("[type=text]").click(function(){
		$('#informationModal').modal('show');
		console.log("input index:"+$("input").index(this));
		inputPos = $("input").index(this);
	});

	$("[type=tel]").click(function(){
		$('#detailTimeModal').modal('show');
		telinputPos = $("[type=tel]").index(this);
		console.log("telinput index:"+telinputPos);
		var posCeil = Math.ceil((telinputPos+1)/6)-1;

		var year = $("[name=detailyear]").eq(posCeil).val();
		var month = $("[name=detailmonth]").eq(posCeil).val();
		var day = $("[name=detailday]").eq(posCeil).val();
		var hour = $("[name=detailhour]").eq(posCeil).val();
		var minute = $("[name=detailminute]").eq(posCeil).val();
		var second = $("[name=detailsecond]").eq(posCeil).val();

		MCtime.MCyear = year;
		MCtime.MCmonth = month;
		MCtime.MCday = day;
		MCtime.MChour = hour;
		MCtime.MCminute = minute;
		MCtime.MCsecond = second;

		$(".changeYear").find(".Dtime-btn-main").find("span").html(year);
		$(".changeMonth").find(".Dtime-btn-main").find("span").html(month);
		$(".changeDay").find(".Dtime-btn-main").find("span").html(day);
		$(".changeHour").find(".Dtime-btn-main").find("span").html(hour);
		$(".changeMinute").find(".Dtime-btn-main").find("span").html(minute);
		$(".changeSecond").find(".Dtime-btn-main").find("span").html(second);
	});

	$(".clickNum").each(function(){
		$(this).click(function(){
			var _num = $(this).html();
			var _type = $(this).parent().parent().attr("type");
			console.log("NUM:"+_num);
			$(this).parent().parent().parent().children().children("span:first").html(addZero(_num));
			localStorage.setItem(_type,_num);
			console.log(localStorage.getItem(_type));
		});
	});

	$(".changeClickNum").each(function(){
		$(this).click(function(){
			var _num = $(this).html();
			var _type = $(this).parent().parent().attr("type");
			$(this).parent().parent().parent().children().children("span:first").html(addZero(_num));
			eval("MCtime.MC"+_type+"="+_num);
			console.log(JSON.stringify(MCtime));
			previewWrite(previewTime());
		});
	});

	$(".PlanDelete").click(function () {
		allowWrite = 1;
		console.log($(".PlanDelete").index(this));
		DeadlineDelete($(".PlanDelete").index(this)+10);
		allowWrite = 0;
	});

	$(".clickModel").each(function(){
		$(this).click(function(){
			console.log("Mlist index:"+$(".clickModel").index(this));
			MlistPos = $(".clickModel").index(this);
			_model = modelList[MlistPos].show;
			$(this).parent().parent().parent().children().children("span:first").html(addZero(_model));
			previewWrite(modelReplace(modelList[MlistPos].content,'#',contentList[ClistPos].content));
		})
	});
	$(".clickContent").each(function(){
		$(this).click(function(){
			console.log("Clist index:"+$(".clickContent").index(this));
			ClistPos = $(".clickContent").index(this);
			_content = contentList[ClistPos].show;
			$(this).parent().parent().parent().children().children("span:first").html(addZero(_content));
			previewWrite(modelReplace(modelList[MlistPos].content,'#',contentList[ClistPos].content));
		})
	});

	$(".FallSwitchBtn[value="+fallCode+"]").removeClass("btn-default");
	$(".FallSwitchBtn[value="+fallCode+"]").addClass("btn-primary");
	$(".FallSwitchBtn[value="+fallCode+"]").attr("disabled","disabled");
	$(".MusicSwitchBtn[value="+musicCode+"]").removeClass("btn-default");
	$(".MusicSwitchBtn[value="+musicCode+"]").addClass("btn-primary");
	$(".MusicSwitchBtn[value="+musicCode+"]").attr("disabled","disabled");
	$(".imgSwitchBtn[value="+mainImgCode+"]").removeClass("btn-default");
	$(".imgSwitchBtn[value="+mainImgCode+"]").addClass("btn-primary");
	$(".imgSwitchBtn[value="+mainImgCode+"]").attr("disabled","disabled");
	$(".BGswitchBtn[value="+backgroundCode+"]").removeClass("btn-default");
	$(".BGswitchBtn[value="+backgroundCode+"]").addClass("btn-primary");
	$(".BGswitchBtn[value="+backgroundCode+"]").attr("disabled","disabled");
	$(".TYPEswitchBtn[colorStyle="+colorStyleCode+"]").removeClass("btn-default");
	$(".TYPEswitchBtn[colorStyle="+colorStyleCode+"]").addClass("btn-primary");
	$(".TYPEswitchBtn[colorStyle="+colorStyleCode+"]").attr("disabled","disabled");
});
$(window).resize(function(){
})