CYC.comment=function (contentId, contentType,options){
	this.init(contentId, contentType,options);
}


jQuery.extend(CYC.comment.prototype,{		
	/**初始化 */
     init:function (contentId, contentType, options){
		this.options = {
			cookieName:"commentsCache",
			namespace: "",
			templateName: "default",
			isPopupForm: false,
			maxCookieNum:3,
			maxCommentLength: 80,
			pageSize:10,
			targetId:""
		}
		 jQuery.extend(this.options, options);
	     this.contentId=contentId;
	     this.contentType=contentType;
	     this.showCountData=this.options.showCountData;
	     this.searchCommentCallback();
		 
     },	  
     /**处理页面上来的 div 或其它用到的 id*/
     getNamespaceId: function(id){
         return "#"+this.options.namespace + id;    	
     },
     /**留言 提交*/
     submitComment: function(){
         var title=jQuery(this.getNamespaceId("commentTitle")).val();
         var content=jQuery(this.getNamespaceId("commentContent")).val();
         var name=jQuery(this.getNamespaceId("commentName")).val();
         var parentId=jQuery(this.getNamespaceId("commentParnetId")).val();
         
         var contentId=jQuery(this.getNamespaceId("contentId")).val();
         var contentType=jQuery(this.getNamespaceId("contentType")).val();
         
         if(contentId == ""){
        	 contentId = this.contentId;
         }
         if(contentType == ""){
        	 contentType = this.contentType;
         }
         
         var vcode=jQuery(this.getNamespaceId("code")).val();
         var instance=this;
         if("" == title || "" == content){
        	 alert("必须要填写标题和内容 !");
        	 return ;
         }else{   
        	     if(content.length > 500){
        	    	 alert("你所输入的内容超过限制");
        	    	 return ;
        	     }
	        	 var commentForm={};
	             if(null != parentId && "" != parentId){
	            	 commentForm.parentId=parentId;
	             }
	             commentForm.contentId=contentId;
	             commentForm.contentType= contentType;
	             commentForm.title=title;
	             commentForm.comment=content;
	             commentForm.nickname=name;
	             
	        	   if(jQuery(this.getNamespaceId("code")).length > 0){
	    		        if("" != vcode){
	    		        	CommentDwrService.checkCode(vcode,{callback:(function (data){
	    		                  if(!data){
	    		                	  alert("验证码错误 ..");
	    		                	 return;
	    		                  }else{
	    		                	  instance.addComment(commentForm);  
	    		                	  jQuery(instance.getNamespaceId("code")).val("");
	    		                      if(instance.options.isPopupForm){
	    		                    	  instance.tb_remove();
	    		                      }
	    		                  } 
	    		        	 })});
	    		        }else{
	    		        	alert("请输入验证码!");
	    		        	return ;
	    		        }
	        	   }else{
	        		     this.addComment(commentForm);  
	                      if(this.options.isPopupForm){
	                    	  this.tb_remove();
	                      }
	        	   }
        	    
         }
     },
     /**搜索留言*/
     searchComment:function(curPage){
    	 /**创建留言分页对象*/
    	 var pagination={};    	
    	 if(this.options.targetId != ""){
    		 pagination.targetId = this.options.targetId;
    	 }else{
    		 pagination.contentId=this.contentId;
    		 pagination.contentType=this.contentType;
    	 }
    	 if(!curPage){
    		 curPage = 1;
    	 }
    	 pagination.curPage=curPage;
    	 pagination.templetName=this.options.templetName;
    	 pagination.pageSize = this.options.pageSize;
    	 pagination.namespace = this.options.namespace;
    	 CommentDwrService.searchComment(pagination,{callback:this.searchCommentCallback.cycbind(this)});
     },
     /**搜索留言回调*/
     searchCommentCallback:function (data){
    	 var instance=this;
    	 if(data){
	    	 jQuery(this.getNamespaceId("comment_list")).empty();
	    	 var commentDiv=jQuery("<div></div>");
	    	 commentDiv.appendTo(this.getNamespaceId("comment_list"));
	    	 commentDiv.html(data);
    	 }
    	 //绑定事件
    	 jQuery(this.getNamespaceId("commentButton")).bind("click",function (){
    		 instance.submitComment();
    	 });
    	 jQuery(this.getNamespaceId("comment_list")+' div.comment_title div.comment_mbg p a').bind("click",function (){
    		   var curPage=jQuery(this).attr("ref");
    		   instance.searchComment(curPage);
    	 });
    	 jQuery(this.getNamespaceId("comment_list")+' .restoreComment').bind("click",function(){
    		     var refs=jQuery(this).attr("ref");
    		     if(refs){
	    		     var title=jQuery(this).prev().val();
	    		     jQuery(instance.getNamespaceId("commentTitle")).val(title)
	    		     
	    		     var values = refs.split(":");
	    		     jQuery(instance.getNamespaceId("commentParnetId")).val(values[0]);
	    		     jQuery(instance.getNamespaceId("contentId")).val(values[1]);
	    		     jQuery(instance.getNamespaceId("contentType")).val(values[2]);	    		     
    		     }else{
    		    	 jQuery(instance.getNamespaceId("commentTitle")).val("");
    		    	 jQuery(instance.getNamespaceId("commentParnetId")).val("");
    		    	 jQuery(instance.getNamespaceId("contentType")).val("")
	    		     jQuery(instance.getNamespaceId("contentId")).val("");
    		     }    		     
    	 });
    	 this.showCookieComments();
    	 jQuery(this.getNamespaceId("comment_list")+' .restoreComment').each(function(){
    		 if(instance.options.isPopupForm){    			 
    	    	 jQuery(this).addClass("thickbox");
    	    	 jQuery(this).attr("href", "#TB_inline?height=380&width=590&inlineId="+ instance.options.namespace + "addComment");    	    	 
    	     }
    	 });
    	 
    	 if(this.options.isPopupForm){    		 
    		 jQuery(this.getNamespaceId("commentButton")).next().css("display", "none");
	    	 /**初始化popup框*/
	    	 jQuery.thickbox(this.getNamespaceId("comment_list")+' .thickbox');
    	 }else{
    		 jQuery(instance.getNamespaceId("addComment")).css("display", "");
    	 }
    	 
    	 var userObject = CYC.Util.getCookieObject("userObject");
 		
 		/**显示登录用户的昵称*/
 		var displayName = userObject.displayName;
 		if(displayName && displayName.trim() != ""){
 			jQuery(instance.getNamespaceId("commentName")).val(displayName); 			
 		}
 		
 		/**留言统计模块添加*/
 		new CYC.stat(this.getNamespaceId("commentTop") +" .stat_buttons", ["Comment.up","Comment.down"]);
     },
	 /**留言或评论*/
	 addComment:function(commentForm){
     	 CommentDwrService.addOrReplyComment(commentForm,{callback:(function (data){
     		    if(data && data != null){
     		    	 alert("非常感谢您的留言！留言正在提交中，您可能在几分钟后才能看到您的留言！");
     		    	 jQuery(this.getNamespaceId("commentTitle")).val("");
    		         jQuery(this.getNamespaceId("commentContent")).val("");
    		         
    		         this.addCommentForm(data);
    		         this.showCookieComments();    		         
     		    }else{
     		    	 alert("操作失败!");
     		    }
     	 }.cycbind(this))});
     },
     /**存储form到cookie*/
     addCommentForm:function (commentForm){    	
    	// 今天时间
    	var d = new Date()
    	var vYear = d.getFullYear()
    	var vMon = d.getMonth() + 1
    	var vDay = d.getDate()
    	var date=vYear+"-"+vMon+"-"+vDay;
    	var commentsCacheStr = jQuery.cookie(this.options.cookieName);
    	var commentsCache = {};
    	if(commentsCacheStr && commentsCacheStr != ""){
    		commentsCache = jQuery.parseJSON(commentsCacheStr);    		
    	}
    	
    	//重组commentForm 只存要的
    	var reformCommentForm={};    	
    	reformCommentForm.createTime=date;  //时间
    	reformCommentForm.id=commentForm.id;  //id 
    	reformCommentForm.title=commentForm.title;  //标题
    	reformCommentForm.comment=commentForm.comment;  //内容
    	reformCommentForm.nickname=commentForm.nickname; //留言名称 
    	reformCommentForm.contentType=commentForm.contentType; //留言的类型
    	reformCommentForm.contentId=commentForm.contentId;   //能留言的id
    	
    	if(reformCommentForm.comment.length > this.options.maxCommentLength){
    		reformCommentForm.comment=reformCommentForm.comment.substring(0, this.options.maxCommentLength)+"...";
    	}   	
    	
    	commentsCache = this.checkCookie(commentsCache);  //将cookie中多的数据删除        
    	commentsCache[reformCommentForm.id] = reformCommentForm;
    	jQuery.cookie(this.options.cookieName, jQuery.toJSON(commentsCache), {path:"/"});
     },
     /**从cookie根据id获取form, 如果不传id则获取所有的form*/
     getCommentForm:function(commentId){
    	 var commentsCacheStr = jQuery.cookie(this.options.cookieName);
    	 
    	 if(commentsCacheStr && commentsCacheStr != ""){
     		var commentsCache = jQuery.parseJSON(commentsCacheStr);
     		if(commentId){
     			return commentsCache[commentId];
     		}else{
     			return commentsCache;
     		}
     	}
     },
     /**根据id删除cookie中的form*/
     removeCommentForm: function(commentId){
    	 var commentsCacheStr = jQuery.cookie(this.options.cookieName);    	 
    	 if(commentsCacheStr && commentsCacheStr != "" && commentId){
     		var commentsCache = jQuery.parseJSON(commentsCacheStr);
     		commentsCache[commentId] = "";
     		var temp = {};
     		for(var commentId in commentsCache){
	       		 if(commentsCache[commentId] != ""){
	       			temp[commentId] = commentsCache[commentId];
	       		 }
	       	 }
     		jQuery.cookie(this.options.cookieName, jQuery.toJSON(temp), {path:"/"});
     	}    	
     },
     /**显示cookie中的comment*/
     showCookieComments: function(){
    	 var i=0;
    	 var cookieCount=0;//计算对应的留言在cookie 的条数
    	 var commentsCache = this.getCommentForm();
    	 jQuery(this.getNamespaceId("cookie_comments")).empty();
    	 //将后面的显示在前面
    	 var commentArray = [];
    	 for(var commentId in commentsCache){
    		 if(jQuery(this.getNamespaceId("comment_list")+' #comment_'+commentId).length > 0){
    			 this.removeCommentForm(commentId);
    		 }else{
	    		 commentArray[i]=commentId;
	    		 i++;
    		 }
    	 }
    	 
    	 /**组div显示 cookie中的值*/
    	 for(var j=commentArray.length-1;j>=0;j--){
    		 var commentId=commentArray[j];
    		 if(commentsCache[commentId].contentType == this.contentType && commentsCache[commentId].contentId== this.contentId ){
    			     var nickname=commentsCache[commentId].nickname;
    			     if("" == nickname || "undefined" == nickname){
    			    	 nickname="查客";
    			     }
    			     cookieCount++
		    		 var commentDiv = jQuery("<div></div>");
		    		 commentDiv.appendTo(this.getNamespaceId("cookie_comments"));
		    		 var appendToHtml="<div class='comment_ly'>" +
		    		       "<div class='comment_tbg'><p></p><span></span><div class='clear'></div></div>"+
		    		          "<div class='comment_mbg'>" +
		    		            "<div class='top'><p><span style='color:#328916'>[最新待审核留言]</span><span class='or'>"+nickname+"</span>发表于:"+commentsCache[commentId].createTime+"</p>"+	    		                         
		    		            "</div>"+
		    		                "<div class='middle'>" +
		    		                    "<h1>"+commentsCache[commentId].title+"</h1>"+
		    		                    "<p>"+commentsCache[commentId].comment+"</p>"+
		    		                "</div>"+         
		    		          "</div>"+
		    		          "<div class='comment_bbg'><p></p><span></span><div class='clear'></div></div>"+
		    		 		"</div>";
		    		 commentDiv.html(appendToHtml)
    		 }
    	 }
    	 
    	 this.countData(cookieCount); //显示最新的计算数据
     },
     /**重新设计 数据的条数*/
     countData:function (cookieCount){
    	    var number=jQuery(this.getNamespaceId("comment_list")+' input.tableCountDate').val();
    	    var countNumber=parseInt(number) + parseInt(cookieCount);
    	    jQuery(this.getNamespaceId("comment_list")+' div.comment_title div.comment_mbg p span.or').text(countNumber+"条");
     },
     /**关闭 弹出框 */
     tb_remove: function() {
	 	jQuery("#TB_imageOff").unbind("click");
		jQuery("#TB_closeWindowButton").unbind("click");
		jQuery("#TB_window").fadeOut("fast",function(){jQuery('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
		jQuery("#TB_load").remove();
		if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
			jQuery("body","html").css({height: "auto", width: "auto"});
			jQuery("html").css("overflow","");
		}
		document.onkeydown = "";
		document.onkeyup = "";
		return false;
	},
	/**当cookie 里的数据 大于指定的，则将前的删除掉*/
	checkCookie:function(commentsCache){
		var num=0;
		var removeId=null;
		for(var commentId in commentsCache){
			if(num==0){
				removeId=commentId;
			}
			num++;
			if(num > parseInt(this.options.maxCookieNum) - parseInt(1)){
				this.removeCommentForm(removeId);
				return this.getCommentForm();
				break;
			}
		}
		return commentsCache;
	}
	
	
});

