function getTreeListSubjectString(sid,id,name){
	
	var disabled="";
	if(!isSubjectComplete(sid)){
		disabled=" disabled=\"disabled\"";
	}
	
	var checked="";
	if(hasSubject(sid)){
		if(getSubject(sid)["included"]){
			checked=" checked=\"checked\"";
		}
	}
	
	//var show="";
	var stringBuffer=new Array();
	//show+="<table class=\"tight\"><tr><td style=\"width: 21px;\">";
	stringBuffer[stringBuffer.length]="<div class=\"itemDiv\"><input id=\""+treeListSubjectInclude+sid+"\" class=\"subjectInclude\" type=\"checkbox\""+disabled+checked+" />";
	//show+="</td><td>";
	stringBuffer[stringBuffer.length]="<span id=\""+treeListSubjectId+sid+"\" class=\"subjectItem\" "+hintKey+"=\"\"> "+id+" "+name+"</span></div>";
	//show+="</td></tr></table>";
	stringBuffer[stringBuffer.length]="<div id=\""+treeListSubjectId+sid+"-\" class=\"listFold\" style=\"line-height:12px; margin-bottom: 3px;\"></div>";
	
	return stringBuffer.join("");
}

function getTreeListCourseString(cid,id,name,campus,last){
	var show="";
	var disabled="";
	/*
	if(!hasCourse(cid)){
		disabled=" disabled=\"disabled\"";
	}
	*/
	
	var checked="";
	if(hasCourse(cid)){
		if(getCourse(cid)["included"]){
			checked=" checked=\"checked\"";
		}
	}
	
	show+="<div class=\"itemDiv\" "+hintKey+"=\"<span class=\'campus\' style=\'color:"+campusColor[campus]+"\'>"+campus+"</span> 校区\">"+"<img class=\"treeListLine\" src=\"images/treeLine"+last+".png\" /> "+"<input id=\""+treeListCourseInclude+cid+"\" class=\"courseInclude\" type=\"checkbox\""+disabled+checked+" /><span id=\""+treeListCourseId+cid+"\" class=\"courseItem\"> "+id+" "+name+"</span></div>";
	
	return show;
}

function showIncludedSubjects(){
	
	var show="";
	
	var sids=new Array();
	
	for(index in $courses){
		var cid=parseInt(index);
		var course=getCourse(cid);
		var sid=course.sid;
		
		if(!arrayHasValue(sids,sid) && course.included && hasSubject(sid)){
			sids[sids.length]=sid;
		}
	}
	
	for(index in $subjects){
		var sid=parseInt(index);
		var subject=getSubject(sid);
		
		if(!arrayHasValue(sids,sid) && subject.included){
			sids[sids.length]=sid;
		}
	}
	
	sids=sortArrayByValue(sids);
	
	for(index in sids){
		var sid=parseInt(sids[index]);
		var subject=getSubject(sid);
		show+=getTreeListSubjectString(subject.sid,subject.id,subject.name);
	}
	
	$("#treeList").html("");
	$("#includedList").html(show);
	
	//readyTreeListSubjectsLoad();
}

function refreshIncludedSubjects(){
	if($treeListTabSelectedIndex!="includedListTab"){
		$("#includedListTab").click();
	}else{
		showIncludedSubjects();
	}
}

function includeSubject(){
	var subjectInclude=includeSubject.arguments[0];
	var sid=parseInt(subjectInclude.attr("id").split(treeListSubjectInclude)[1]);
	var subject=getSubject(sid);
	subject.included=subjectInclude.attr("checked");
}

function includeCourse(){
	var courseInclude=includeCourse.arguments[0];
	var cid=parseInt(courseInclude.attr("id").split(treeListCourseInclude)[1]);
	var course=getCourse(cid);
	course.included=courseInclude.attr("checked");
	
	if(course.included){
		var sid=course["sid"];
		var subjectInclude=$("#"+treeListSubjectInclude+sid);
		if(!subjectInclude.attr("checked")){
			subjectInclude.attr("checked",true);
			getSubject(sid)["included"]=true;
		}
	}
}

function readyTreeListCoursesLoad(){
	
	//$("span.courseItem").unbind();
	
	$("span.courseItem").live("click",function(){
		clickTreeListCourse(this.id.split(treeListCourseId)[1]);
	});
	
	$("span.courseItem").live("mouseover",function(){
		$(this).addClass("mouseOver");
	});
	$("span.courseItem").live("mouseout",function(){ 
		$(this).removeClass("mouseOver");
	});
	
	/*$("div.itemDiv["+hintKey+"]").unbind("mousemove");
	$("div.itemDiv["+hintKey+"]").unbind("mouseout");
	
	$("div.itemDiv["+hintKey+"]").bind("mousemove",function(e){
		showHint($("#"+hintKey),$(this),hintKey,e);
	});
	
	$("div.itemDiv["+hintKey+"]").bind("mouseout",{"hint":$("#"+hintKey)},hideHint);*/
	
	$("input.courseInclude").live("click",function(){
		var courseInclude=$(this);
		var cid=parseInt(courseInclude.attr("id").split(treeListCourseInclude)[1]);
		if(hasCourse(cid)){
			includeCourse(courseInclude);
		}else{
			//$(this).attr("checked",!$(this).attr("checked"));
			loadCourseDetail(cid,includeCourse,courseInclude);
		}
		this.blur();
	});
	
	/*$("input.courseInclude").live("focus",function(){
		this.blur();
	});*/
		
}

function loadSubjectAscription(subjectItem,hintKey,e){
	var subject=getSubject(subjectItem.attr("id").split(treeListSubjectId)[1]);
	
	if(!arrayHasKey(subject,"ascription")){
		
		subjectItem.attr(hintKey,getLoadingHTML());
		
		$.post("servlet/SubjectsAscription",{id:subject.id},function(data){

			var ascription=data.split(valueSplit);
			
			for(index in ascription){
				if(ascription[index]==""){
					ascription[index]=defaultAscription[index];
				}
			}
			
			subject.ascription="<b>课程归属</b><br>"+ascription[0]+"<br>"+ascription[1]+"<br>"+ascription[2];
			
			subjectItem.attr(hintKey,subject.ascription);
			
			showHint($("#"+hintKey),subjectItem,hintKey,e);
			
		});
		
	}else{
		subjectItem.attr(hintKey,subject.ascription);
	}
}

function readyTreeListSubjectsLoad(){
	
	//$("span.subjectItem").unbind();
	
	$("span.subjectItem").live("click",function(){
		clickTreeListSubject(this);
	});
	
	//$("span[id^="+treeListSubjectId+"]").unbind("mousemove");
	//$("span[id^="+treeListSubjectId+"]").unbind("mouseout");
	
	$("span[id^="+treeListSubjectId+"]").live("mousemove",function(e){
		if($(this).attr(hintKey)==""){
			loadSubjectAscription($(this),hintKey,e);
		}
		//showHint($("#"+hintKey),$(this),hintKey,e);
	});
	
	//$("span[id^="+treeListSubjectId+"]").bind("mouseout",{"hint":$("#"+hintKey)},hideHint);
	
	$("span.subjectItem").live("mouseover",function(e){
		$(this).addClass("mouseOver");
	});
	$("span.subjectItem").live("mouseout",function(){ 
		$(this).removeClass("mouseOver");
	});
	
	$("input.subjectInclude").live("click",function(){
		var subjectInclude=$(this);
		var sid=parseInt(subjectInclude.attr("id").split(treeListSubjectInclude)[1]);
		if(hasSubject(sid)){
			includeSubject(subjectInclude);
		}else{
			$(this).attr("checked",!$(this).attr("checked"));
			loadSubjectDetail(sid);
		}
		this.blur();
	});
	
	/*$("input.subjectInclude").live("focus",function(){
		this.blur();
	});*/
	
}


var $bufferSize=50;
var $treeListSubjectsBuffer=null;
var $lastLoading=null;
var $stillLoading=false;
function loadTreeListSubjects(list){
	$stillLoading=true;
	if($treeListSubjectsBuffer!=null){
		
		var stringBuffer=new Array();
		stringBuffer[stringBuffer.length]=list.html();
		
		for(var i=0;i<$bufferSize && $treeListSubjectsBuffer.length>0;i++){
			
			var subject=$treeListSubjectsBuffer.pop();
			var value=subject.split(valueSplit);
			
			var sid=parseInt(value[0]);
			var id=value[1];
			var name=value[2];
			
			var subjectObject={sid:sid,id:id,name:name};
			addSubjects(subjectObject);
			
			stringBuffer[stringBuffer.length]=getTreeListSubjectString(sid,id,name);
		}
		
		list.html(stringBuffer.join(""));
		stringBuffer=null;
	}
	$stillLoading=false;
}

function restoreTreeListSubjectsBuffer(){
	$treeListSubjectsBuffer=null;
	$lastLoading=null;
	$stillLoading=false;
}

function showTreeListSubjects(list,data){
	
	restoreTreeListSubjectsBuffer();
	
	if(data==""){
		
		data="<table class=\"treeListHint\">";
		
		if($(".campusSelector:checked").size()!=0){
		
			data+="<tr><td colspan=\"2\">在";
			$(".campusSelector:checked").each(function(){
				data+=" "+$(this).val();
			});
			data+=" 校区中</td></tr>";
		}
		
		data+="<tr><td colspan=\"2\">未能查询到 <b>"+getQueryModeName()+"</b> 为</td></tr>";
		data+="<tr><td colspan=\"2\"><b>"+getQueryValue()+"</b> 的课程</td></tr>";
		
		if($(".campusSelector:checked").size()==0){
			data+="<tr><td colspan=\"2\">原因: 您没有勾选任何校区</td></tr>";
		}
		
		data+="<tr><td colspan=\"2\">&nbsp;</td></tr>";
		data+="<tr><td colspan=\"2\"><b>提示</b></td></tr>";
		data+="<tr valign=\"top\"><td>1.</td><td>您是否设置了过多的上课时间约束？</td></tr>";
		data+="<tr valign=\"top\"><td>2.</td><td>查询类型是否与您输入的查询条件不匹配？例如，选择“课程号”却输入课程名称进行查找。</td></tr>";
		data+="<tr valign=\"top\"><td>3.</td><td>在查询面板中勾选更多的校区，以扩大对于课程所在校区的查询范围。</td></tr>";
		data+="<tr valign=\"top\"><td>4.</td><td>如果想通过运动项目查询体育课，例如“男生篮球”，请注意选择<b>教师姓名</b>进行查找。</td></tr>";
		data+="<tr valign=\"top\"><td>5.</td><td>可以参考右上角的 视频教程。</td></tr>";
		data+="<tr valign=\"top\"><td>6.</td><td>向<a href=\"http://bbs.lehu.shu.edu.cn/ArticleList.aspx?cid=18\" target=\"_blank\">乐乎论坛</a>反映，或者与我们<a href=\"mailto:support@kernelstudio.org\">取得联系</a>。</td></tr>";
		data+="</table>";
		
		list.html(data);
		
	}else{	// TODO 分段载入过长的课程列表，防止浏览器锁死
		
		list.html("");
		
		var subjects=data.split(itemSplit);
		
		subjects.reverse();
		
		$treeListSubjectsBuffer=subjects;
		
		loadTreeListSubjects(list);
		
		/*for(index in subjects){
			
			var subject=subjects[index];
			
			var value=subject.split(valueSplit);
			
			var sid=parseInt(value[0]);
			var id=value[1];
			var name=value[2];
			
			var subjectObject={sid:sid,id:id,name:name};
			addSubjects(subjectObject);
			
			show+=getTreeListSubjectString(sid,id,name);
			
		}
		
		list.html(show);*/
		
		//readyTreeListSubjectsLoad();
	}
}

function showTreeListCourses(list,data){
	
	if(data==""){
		
		data="无教师信息，请修改条件后再查询！";
		
		list.html(data);
		
	}else{
		
		var courses=data.split(itemSplit);
		
		var last="";
		
		var sorted=new Array();
		
		for(index in courses){
			
			if(index==courses.length-1){
				last="Last";
			}
			
			var course=courses[index];
			
			var value=course.split(valueSplit);
			
			var cid=parseInt(value[0]);
			var id=parseInt(value[1]);
			var name=value[2];
			var campus=value[3];
			
			sorted[cid]={id:id,name:name,campus:campus,last:last};
		}
		
		sorted=sortArrayByKey(sorted);
		
		var stringBuffer=new Array();
		
		for(index in sorted){
			var course=sorted[index];
			stringBuffer[stringBuffer.length]=getTreeListCourseString(index,course.id,course.name,course.campus,course.last);	
		}
		
		list.html(stringBuffer.join(""));
		stringBuffer=null;
		
		//readyTreeListCoursesLoad();
	}
}

function clickTreeListSubject(subject){
	var courses=$("#"+subject.id+"-");
	
	//courses.toggleClass("listFold");
	
	var sid=parseInt(subject.id.split(treeListSubjectId)[1]);
	
	clearCourseTimeTable();
	
	loadSubjectDetail(sid);
	
	courses.toggle("fast");
	
	if(courses.html()==""){
		
		clearCourseTimeTable();
		
		courses.html(getLoadingHTML());
		
		var value=getQueryValue();
		var times=getTimeCubeString();
		var campus=getCampusSelection();
		
		if($treeListTabSelectedIndex=="includedListTab"){
			value="";
			times="";
			campus="";
		}
		
		$.post("servlet/TreeList",{sid:sid,mode:$("#queryMode").attr("value"),value:value,times:times,campus:campus},function(data){
			
			showTreeListCourses(courses,data);
			
		});
		
	}
	
	$("#infoPanel").idTabs("detailRender");
	$("#timePanel").idTabs("timeTable");
}

function clickTreeListCourse(cid){

	loadCourseDetail(cid);
	
	$("#infoPanel").idTabs("detailRender");
	$("#timePanel").idTabs("timeTable");
	
}

/*function loadTreeList(){
	
	$.post("servlet/TreeList",function(data){
		
		showTreeListSubjects($("#treeList"),data);
		
	});
	
}*/

function readyTreeListLoad(){
	
	readyTreeListSubjectsLoad();
	
	readyTreeListCoursesLoad();
}

var $treeListTabSelectedIndex="treeListTab";

function readyTreeListAction(){
	
	readyTreeListLoad();
	
	$("#treeListTab").click(function(){
		if($treeListTabSelectedIndex!=$(this).attr("id")){
			$treeListTabSelectedIndex=$(this).attr("id");
			
			if(getQueryValue()!=""){
				query();
			}
		}
	});
	
	$("#treeList").scroll(function(){
		
		if($treeListSubjectsBuffer!=null && $treeListSubjectsBuffer.length>0){
			
			if(this.scrollHeight-$(this).height()<=this.scrollTop+this.scrollHeight/6){
				// Dynamically load when scroll to 1/6 position from the bottom.
				var now=new Date();
				if(!$stillLoading && verifyFrequently($lastLoading,now,1500)){
					$lastLoading=now;
					loadTreeListSubjects($(this));
				}
			}
		}
	});
	
	$("#includedListTab").click(function(){
		if($treeListTabSelectedIndex!=$(this).attr("id")){
			$treeListTabSelectedIndex=$(this).attr("id");
			
			clearCurrentDetail();
			clearDetailRender();
			
			showIncludedSubjects();
		}
	});
	
}
