$(function(){
loginStatus();//读取用户头像
	 	var userid = $.cookie("userid");
	 	var professorId = GetQueryString("professorId");
	 	var name;
	 	if(professorId){

	 		var subjectShow = function (data){
				if(data != undefined &&  data.length != 0 ){
					var subs = new Array();
					if(data.indexOf(',')){
						subs = data.split(',');
					}else{
						subs[0] = data;
					}
					if(subs.length>0){
						for (var i = 0; i < subs.length; i++) {							
							$("#subjectShow").append("<div class='acad'>"+subs[i]+"</div>");		
								
						};
					}	
				}			
			}
			var industryShow = function (data){

				if(data != undefined && data.length != 0  ){

					var subs = new Array();
					if(data.indexOf(',')){
						subs = data.split(',');
					}else{
						subs[0] = data;
					}

					if(subs.length>0){
						for (var i = 0; i < subs.length; i++) {
							
							$("#industryShow").append("<li>"+subs[i]+"</li>");		
								
						};
					}	
				}			
			}

			// var eduBgShow = function (data){

			// 	if(data != undefined && data.length != 0  ){

			// 		var subs = new Array();
			// 		if(data.indexOf(',')){
			// 			subs = data.split(',');
			// 		}else{
			// 			subs[0] = data;
			// 		}

			// 		if(subs.length>0){
			// 			for (var i = 0; i < subs.length; i++) {
			// 				$("#industryList").append("<div class='acad'>"+ subs[i] +"<span class='remove'><img src='images/move.png'></span></div>");
			// 				$("#industryShow").append("<li>"+subs[i]+"</li>");		
								
			// 			};
			// 		}	
			// 	}			
			// }

			var eduBgShow = function(data) {

				if(data.length>0){
					for (var i = 0; i < data.length; i++) {

						var showHtml = "<li>";
						if(typeof(data[i].school) !== "undefined"){
							showHtml += data[i].school;
						}else{
							showHtml += "不详";
						}
						showHtml += "-";
						if(typeof(data[i].college) !== "undefined"){
							
							showHtml += data[i].college;
						}else{
							showHtml += "不详";
						}
						showHtml += "-";
						if(typeof(data[i].major) !== "undefined"){
							
							showHtml += data[i].major;
						}else{
							showHtml += "不详";
						}
						showHtml += "-";
						if(typeof(data[i].degree) !== "undefined"){
							
							showHtml += data[i].degree;
						}else{
							showHtml += "不详";
						}
						showHtml += "-";
						if(typeof(data[i].year) !== "undefined"){
							
							showHtml += data[i].year;
						}else{
							showHtml += "不详";
						}
						showHtml += "</li>";
						 $("#eduBgShow").append(showHtml);
						// $("#eduBgShow").append("<li>"+data[i].school+"－"+data[i].college+"－"+data[i].major+"－"+data[i].degree+"－"+data[i].year+"</li>");
						
					}
				}
			}

			var timeJobShow = function(data) {

				if(data.length>0){
					for (var i = 0; i < data.length; i++) {
						$("#timeJobShow").append("<li>"+data[i].company+"－"+data[i].title+"－"+data[i].startMonth+"-"+data[i].stopMonth+"</li>");
					}
				}
			}

			var projectShow = function(data){
				if(data.length>0){
					for (var i = 0; i < data.length; i++) {
						if(data[i].descp=="undefined"){
							$('.spancon').css({display:"none"});
						}  
						$("#projectShow").append("<li>名称："+data[i].name+"<br><span class='spancon'>内容："+data[i].descp+"</span></li>");
					}  
				}
			}

			var paperShow = function(data){
				if(data.length>0){
					for (var i = 0; i < data.length; i++) {
						$("#paperShow").append("<li>"+data[i].name+"</li>");
						
					}
				}
			}

			var patentShow = function(data){
				if(data.length>0){
					for (var i = 0; i < data.length; i++) {
						$("#patentShow").append("<li>"+data[i].name+"</li>");
						
					}
				}
			}

			var honorShow = function(data){
				if(data.length>0){
					for (var i = 0; i < data.length; i++) {
						$("#honorShow").append("<li>"+data[i].name+"</li>");
						
					}
				}
			}
			var researchAreaShow = function ($datas,$datarecords){
				if($datas != undefined &&  $datas.length != 0 ){
					for(var i =0 ; i< $datas.length;++i){
						var $data = $datas[i];
						var $photos = [];
						//获取头像
						if($datarecords.length>0){
							$photos = getRecords($datarecords,$data.caption);
						}
						var isAgree = $.inArray(userid, $photos);

						var showDiv= "<div class='listbox listbox-browse clear'><div class='list-browse'><span class='like'>"+$data.count+"</span>"+$data.caption+"</div><span class='plus' data-pid='"+$data.professorId+"' data-caption='"+$data.caption+"' data-isagree='"+isAgree+"'></span><div class='like-num'>";
						if($photos.length>10){
							showDiv += "<div class='triangleR'></div>";
						}
						
						if($photos.length>0){
							for(var j =0 ; j< $photos.length;++j){
								showDiv += "<span class='like-people'><img class='like-h' src='/images/head/"+$photos[j]+"_s.jpg'></span>";
								
							} 
						}
						showDiv += "</div></div>";
						$("#researchAreaShow").append(showDiv);
						
						$(".like-h").load(function(){								
						})
						.error(function(){
							$(this).attr("src","/images/default-photo.jpg");
						});	
							
					}
				}			
			}
			var getRecords = function ($researchAreaLogs,caption){
			     var ret=[];
			     for(var i = 0 ;i < $researchAreaLogs.length ; i++){
			     	if(caption==$researchAreaLogs[i].caption){
			     		ret.push($researchAreaLogs[i].opreteProfessorId);
			     	}
			     }
			     return ret;
			}


			$("#researchAreaShow").on("click",".plus",function(){
				if(userid && userid != null && userid != "null"){
					$.ajax({
						"url" : $(this).data("isagree")>-1?"/ajax/researchArea/unAgree":"/ajax/researchArea/agree",
						"type" : "POST",
						"data" : {"targetId":$(this).data("pid"),"targetCaption":$(this).data("caption"),"opId":userid},
						"contentType" : "application/x-www-form-urlencoded",
						"success" : function($data) {
							if ($data.success) {
								location.reload(true);
							} else {
								$.MsgBox.Alert("message",$data.msg);
							}
						}
					});
				}else{
					$.MsgBox.Alert("消息","请登录后点赞");
					/*location.href="login.html"*/
				}
				
			})

	    	$.get("/ajax/professor/info/" + professorId, function($data) {
	    			if ($data.success) {
						var $info = $data.data;
						if ($info) {
							//展示专家的信息
							$("#nameS").text($info.name);
							$("#titleS").text($info.title);
							$("#orgNameS").text($info.orgName);
							$("#headImage").attr("src","/images/head/"+professorId+"_l.jpg");
								$("#headImage").load(function(){									
								})
								.error(function(){
									$("#headImage").attr("src","/images/default-photo.jpg");
								});
							$("#orgImage").attr("src","/images/org/"+$info.orgId+".jpg");
								$("#orgImage").load(function(){									
								})
								.error(function(){
									$("#orgImage").attr("src","/images/default-icon.jpg");
								});
							$("#descpS").text($info.descp);
							//显示专家信息到保存数据
							name=$info.name;
							$("#name").val($info.name);
							$("#title").val($info.title);
							$("#orgId").val($info.orgId);
							$("#organ").attr("href","organization-brow.html?orgId="+$info.orgId+"");
							//console.log($info.orgId);
							$("#orgName").val($info.orgName);
							$("#department").val($info.department);
							$("#descp").val($info.descp);
							//展示专家的学科
							subjectShow($info.subject);
							//研究方向
							if ($info.researchAreas) {
								researchAreaShow($info.researchAreas,$info.researchAreaLogs);
							}
							//展示专家的行业
							industryShow($info.industry);
							//教育北京
							if ($info.edus) {
								eduBgShow($info.edus);
							}
							//兼职
							if ($info.jobs) {
								timeJobShow($info.jobs);
							}
							//项目
							if ($info.projects) {
								projectShow($info.projects)
							}

							//论文
							if ($info.papers) {
								paperShow($info.papers);
							}
							//专利
							if ($info.patents) {
								patentShow($info.patents);
							}
							//荣誉
							if ($info.honors) {
								honorShow($info.honors);
							}
							 
					//下滑滚动不覆盖底部 
							var d;
							var t;
							$(function(){
							/*向下滚动时，header背景变半透明*/
							var top5=$(".content-left").height();
						
							var top4=$("#container").height();				
							var top3=$(window).height();						
							$(document).scroll(function(){
							var top1 =$(document).scrollTop();	
							var top2=$("#container").height()-top3+(top3-80-top5)-10;//变成绝对定位	
							if(top1>=300){
										$(".content-left").css({"position":"fixed","top":"80px"});
										if(top1>=top2)
									{
										$('.information-content').css("position","static");
										$(".content-left").css("position", "absolute");		
										$(".content-left").css("top", top4-top5-10+"px");													
									}
									else{
											$('.information-content').css("position","relative");
											$(".content-left").css({"position":"fixed","top":"80px"});	
									}	
								}
							else{
							$(".content-left").css({"position":"static"});	
							
							}
							
							})	
							});
							//下滑滚动不覆盖底部 结束
						}
					}
				}
			);
	    }
		$("#hsearch").on("click",function (){
	   		var searchContent = $("#hsearchContent").val();
	   		location.href = "search.html?searchContent="+searchContent;
	  });



//进入自己的页面，上传图像部分
$(".head-left").hover(function(){
	$(".replace-photo").animate({"bottom":"0px"});						   						   
	},function(){
	$(".replace-photo").animate({"bottom":"-50px"});	
		
		})
//专家信息点击换背景颜色
$(".subsidebar").click(function(){
	$(".subsidebar").removeClass("subcolor");
	$(".subsidebar").eq($(".subsidebar").index(this)).addClass("subcolor");						  
});
//拿到点击的顺序，然后求出局文档的距离
$(".subsidebar").click(function(){
	var index=$(".subsidebar").index(this);
	var offset=$(".introduction").eq(index).offset();

		$("body").animate({ 
			scrollTop:offset.top-80 //��body��scrollTop����pos��top����ʵ���˹��� 
			},1000); 
		 
		 })

//科研资源
	$.ajax({		
		"url":"/ajax/resource/qapro",
		"type":"get",
		"data":{"professorId":professorId},
		"async": true,
		"success":function(data){
			//console.log(data);
			if(data.data.length==0){
				$("#infor-browse").css("display","none");
				$(".resoubtn").css("display","none");
			}
			if(data.data.length > 0 && data.data.length <= 3){
				$("#infor-browse").css("display","block");
				$(".resoubtn").css("display","none");
			}
			var add="";
			if(data.success)
				{
					for(var i=0;i<data.data.length;i++){
						add='<div class="sharesrc">'
						add+='<div class="shareshow">'
	                	add+='<a class="remess" resourceId='+data.data[i].resourceId+'><img src="/images/resource/'+data.data[i].resourceId+'.jpg" width="100%" height="100%" class="resourceImg"></a>'
	                 	add+='<div class="shareopeart"><a class="sharebtn">咨询</a><a class="sharebtn applicant">申请</a></div>'
	             		add+='</div>'
	             		add+='<p>资源名称：<span class="presou">'+ data.data[i].resourceName+'</span></p>'
	             		add+='<p class="briefinfor">简介:'+data.data[i].supportedServices+'</p>'
	        			add+='</div>'
	        			$("#sharescrollbox").append(add);
						$('.applicant').eq(i).attr("resourceId",data.data[i].resourceId);
						
						$(".resourceImg").eq(i).attr("src","/images/resource/"+data.data[i].resourceId+".jpg");
						$(".resourceImg").load(function(){})
							.error(function(){
								$(this).attr("src","/images/default-resource.jpg");
							});	
						
						add="";
					}
					//资源轮播
					var $content = $(".sharescrollbox");
					var childcount = $content.find(".sharesrc").length; 
					Carousel(3,3, childcount, $content, $(".resounext"), $(".resouprev"));
					
					function Carousel(inde, num, childcount, obj, next, prev) {
						next.click(function() {	
							if (!obj.is(":animated")) { 
								if (num < childcount) { 
								
									num++;
									obj.animate({
										left: "-=212px"
									}, 600);
								}
							}
						});
						prev.click(function() {
							if (!obj.is(":animated")) {
								if (num > inde) { 
									num--;
									obj.animate({
										left: "+=212px"
									}, 600);
								}
							}
						});
					}
				}
				else
				{
					$.MsgBox.Alert("消息","系统异常!");
				}
		},
		"error":function(){$.MsgBox.Alert('message','failddd')}
	});
	
	function getIdentity(professorId){		
		$.ajax({	
		"url":"ajax/professor/"+professorId,
		"type":"get",
		"async": false,
		"success":function(data){
			if(data.success)
			{																	
				//console.log(data);
				$("option")[0].value=data.data.name;
				$("option")[1].value=data.data.organization.name;
				//console.log($("option")[0].value);
				//console.log($("option")[1].value);
			}
			else
			{
				$.MsgBox.Alert("消息","系统异常!");
			}
		},
		"error":function(){$.MsgBox.Alert('message','failddd')}
		})	
	}
	//查看资源详细信息
	$('#sharescrollbox').on("click",'.remess',function(){
		var resourceID=$(this).attr("resourceId");
		ResourceMessage();
		$.ajax({		
			"url":"/ajax/resource/"+resourceID,
			"type":"get",
			"async": true,
			"success":function(info){
				if(info.success)
					{
					console.log(info);
					$("#resourceName").text(info.data.resourceName);
					$("#supportedServices").text(info.data.supportedServices);
					$("#hopePayMethod").text(info.data.hopePayMethod) ;
					$("#cooperationNotes").text(info.data.cooperationNotes) ;
					$("#subject").text(info.data.subject);
					$("#industry").text(info.data.industry);
					$("#descp").text(info.data.descp);
					$("#professor").text(name);
					$(".resouImage").attr("src","/images/resource/"+resourceID+".jpg");
					$(".resouImage").load(function(){})
						.error(function(){
							$(this).attr("src","/images/default-resource.jpg");
						});
					}
					else
					{
						$.MsgBox.Alert('message',"系统异常!");
					}
			},
			"error":function(){$.MsgBox.Alert('message','failed')}
		});  
	})
//资源申请入口
	$('.introduction').on("click",'.applicant',function(){
		if(userid && userid != null && userid != "null"){
			ResourceApply();//调用资源申请HTML创建函数
			$(".limitBox").removeClass("limitBox");
	        $(".limitwords").removeClass("limitwords");
	        $(".limitwordbox").removeClass("limitwordbox");
			//获取当前时间并且格式化时间
			var myDate = new Date();
			var nowYear = myDate.getFullYear();
			var nowMonth = myDate.getMonth()+1;
			var nowDate = myDate.getDate();
			if(nowMonth<10){
				nowMonth="0"+nowMonth.toString();
			}
			if(nowDate<10){
				nowDate="0"+nowDate.toString();
			}
			var now = nowYear + "-" + nowMonth + "-" + nowDate;
			$( "#datepicker").val(now);
			
			//console.log(now);
			
			$( "#datepicker" ).datepicker({ "dateFormat":" yy-mm-dd"});
			//console.log(name);
			$(".timelo").css("display","none");
			$(".namecon").text(name);
			$(".applysure").hide();
			$(".btnboxup").hide();
			var index1=$(this).parent().parent().parent().index();
			var resName=$('.presou').eq(index1).text();
			//console.log(index1);
			var m=console.log();
			var resourceID=$(this).attr("resourceId");
			$(".resouImage").attr("src","/images/resource/"+resourceID+".jpg");
			$(".resouImage").load(function(){})
				.error(function(){
					$(this).attr("src","/images/default-resource.jpg");
				});
			
			//console.log(resourceID);
			//
			$(".log").text(resName);
			
			getIdentity(userid);
			
			$("#deliver").on("click",function()
					{	
				
					var $data = {};
					$data.demandId = userid;
					$data.resourceId=resourceID;
					$data.detailDemand=$(".detail").val();
					//去除时间里面的-  和字符串前后的空格
					$data.deliverTime=replaceStr($.trim($(".dealTime").val()));
				    //alert(replaceStr($.trim($(".dealTime").val())));
				    //alert(replaceStr($.trim($(".dealTime").val())).length);
					
					$data.operationStatus=1;
					$data.applysquare=$("select option:selected").val();	
					//console.log($data.applysquare);
					
					
					$.ajax({
						"url" : "/ajax/operation",
						"type" : "POST",
						"success" : function(rdata) {
							if (rdata.success) {
								$.MsgBox.Alert('message','资源"'+ resName +'"申请发送成功!');
								$(".blackcover").remove();
								$("body").css("position","static");
								//location.reload(true);
							} else {
								$.MsgBox.Alert('message','资源"'+ resName +'"申请发送失败，请重新申请!');
							}
						},
						"data" :  $data,
						"beforeSend":function(){/*console.log(this.data)*/},
						"contentType" :  "application/x-www-form-urlencoded",
						dataType : "json"
					});
			});
		}else{
			$.MsgBox.Alert("消息","您还未登录，请登录之后进行资源申请");
		}	
	});
	
	
	//=====================================
	//事件封装
/*	function addEvent(obj,type,handler){
	    if(obj.addEventListener){
	        obj.addEventListener(type,handler,false);
	    }else if(obj.attachEvent){
	        obj.attachEvent('on'+type,handler);
	    }
	}

	function removeEvent(obj,type,handler){
	    if(obj.removeEventListener){
	        obj.removeEventListener(type,handler,false);
	    }else if(obj.detachEvent){
	        obj.detachEvent("on"+type,handler);
	    }
	}*/
	
	
	//===============点击咨询==============
	var consultBtn = $("#consultbtn");
	var userid = $.cookie("userid");//登陆人id====重复代码
 	var professorId = GetQueryString("professorId");//专家id====重复代码
 
	function consultHandler(){
		ConsultApply();
		//点击的发送
		var sendConsultBtn = $("#sendConsultBtn");
		sendConsultBtn.on("click",sendConsultHandler);
		
		if(userid && userid != null && userid != "null"){
			$.ajax({
				"url" :"/ajax/professor/"+ professorId,
				"type" : "get",
				"data" : {"professorId":professorId},
				"contentType" : "application/x-www-form-urlencoded",
				"success" : function(response) {
					if (response.success) {
						//console.log(response);
						$("#professorName").text(response.data["name"]);
						$("#professorTitle").text(response.data["title"]);
						
						if(response.data["department"] == "" || response.data["department"] == null){
							$("#profOrganization").text(response.data["organization"]["name"]);
						}else{
							$("#profDepartment").text(response.data["department"]+",");
							$("#profOrganization").text(response.data["organization"]["name"]);
							
						}
						if(response.data["adress"] == "" || response.data["adress"] == null ){
							$("#adress").html("");
						}else{
							$("#profAdress").text(response.data["adress"]);
						}

						
					} else {
						$.MsgBox.Alert("message","请登录");
					}
				},
				"complete":function(){
					
				}
			});
		}
	};
	
	//点击咨询
	consultBtn.on('click',consultHandler);	
	var consultId;
	//发送咨询申请处理函数
	function sendConsultHandler(){
		var consult_type = $(".clicknow").text();//咨询类型
		var consult_title = $("#consultTitle").val();//咨询主题
		var consult_content = $("#consultContent").val();//咨询内容
		var consultStr = {
				"consultType":consult_type,
				"consultTitle":consult_title,
				"consultContant":consult_content,
				"professorId":professorId,
				"consultantId":userid
		};
		
		/*if(consult_type == '' || consult_title == '' || consult_content == ''){
			$.MsgBox.Alert("message","请填写完整");
		};*/
		if(consult_type == ''){
			$.MsgBox.Alert("消息","请选择联系目的");
		}
		if(consult_title == ''){
			$.MsgBox.Alert("消息","请填写咨询目的");
		}
		if(consult_content == ''){
			$.MsgBox.Alert("消息","请填写咨询内容");
		}
		
		if(userid && userid != null && userid != "null" && consult_type != '' &&
				consult_title != '' && consult_content != ''
		){
			
			$.ajax({
				"url" :"/ajax/consult",
				"type" : "post",
				//传值：咨询类型、主题、内容、专家id、申请人id
				"data" : consultStr,				
				"contentType" : "application/x-www-form-urlencoded",
				"beforeSend":function(){/*console.log(this.data)*/},
				"dataType" : "json",
				"success" : function(response) {
					
					
					consultId = response.data;//咨询id
					
					
				},
				"error":function (){
					$.MsgBox.Alert("消息","咨询申请失败");
				},
				
				"complete":function(){
					//$(".consultapply").remove();
					$(".blackcover").remove();
					$("body").css("position","static");
					$.MsgBox.Alert("消息","咨询申请成功");
				},
			});
		}

	}

	
	
	
})

