window.modManageCreated={};
window.hs_cache=[];
//var ModuleLoadder=Class.create();
function modToggle(e){
    return ;
	if(!e)
		e=window.event;
	var element=Event.element(e);
	var node=element.parentNode.parentNode;
	var id=node.id;
	if(id!="postsList"){
		var modcontent=$$("#"+id+" div.modcontent")[0];

		if(window.ie&&!modcontent.fixed){
			var height=modcontent.offsetHeight;
			if(height%2!=0){
				modcontent.setStyle('height',height+1);
				height=height+1;
			}
			modcontent.fixedH=height;
			modcontent.fixed=true;
		}
		var fixHeight=function(){
			if(window.ie&&$(modcontent.parentNode).offsetHeight>1){
				$(modcontent).setStyle('height',modcontent.fixedH-18);
				$(modcontent.parentNode).setStyle('height',modcontent.fixedH);
			}
		}
		if(!modcontent.slider){
			modcontent.slider=new Fx.Slide(modcontent, {duration: 500,onComplete:fixHeight});
			var toggleDiv=$$("#"+id+" div.toggle")[0];
			modcontent.toggleDiv=toggleDiv;
		}
		modcontent.toggleDiv.className=modcontent.toggleDiv.className=="toggle"?"toggledown":"toggle";
		modcontent.slider.toggle();
	}else{//如果是文章列表
		var elements=$$("#postsList div.metaword").extend($$("#postsList div.artcontrol"));
			elements.each(function(element){
				element.style.display=(element.style.display=="none")?"block":"none";
			});
	}
}

var ModuleLoadder=new Class({
	initialize:function(config){
		var mods=this.getModules();
		for(var i=0;i<config.length;i++){
			if(mods[config[i]]) 
                new mods[config[i]]();
			// 自定义模块
			if(config[i].substring(0,11)=="userDefined"){
				var id=config[i].substring(11);

				new UserDefinedMod(id);
			}
		}

	},
	getModules:function(){
		return window.modules;
	}
});


//var BaseModule=Class.create();

BaseModule=new Class({
	setOptions: function(options){
		this.options = {
			bindFunc: Class.empty,
			manageFunc:Class.empty
		}
		Object.extend(this.options, options || {});

	},

	initialize:function(){
		this.END_POINT="/control/control.php";
		this.needSession=true;
		this.session_id=window.session_id;
		this.total=0;
		this.perPage=0;
		this.currentPage=1;

		//this.init();
		this.id="";
		this.contentId="";
		this.jstId="";
		this.op="";
		//this.params={user_id:window.user_id};
		this.params={};
		this.cache_id=false;
	},
	loadFunction:function(e,para){
		if(window.isOwner&&!window.modManageCreated[this.id]&&typeof(in_main)!="undefined"){
			this.insertManageFunction();
			window.modManageCreated[this.id]=true;
			this.manageCreated=true;
		}

        // check cache, render cache if have.
        if(para&&para.cache_id&&window.hs_cache&&window.hs_cache[para.cache_id]&&typeof(window.hs_cache[para.cache_id])!="undefined"){
            this.cache_id=para.cache_id;
            // TODO : to render cache;
        } else{
        }
        // 更新参数
        if( typeof(para) == "object" ) this.params=Object.extend(this.params,para);
        if( this.hs_pager ) this.currentPage=this.params.page=$("hs_page_e").value;
	    this._post(this.op,this.onLoadFunction.bind(this),this.params);
	},
	renderFunction:function(){
		this.data._MODIFIERS=TT_Filters;
		var result = TrimPath.processDOMTemplate(this.jstId, this.data);
		//清空数据
		//this.data=false;
		$(this.contentId).innerHTML=result;
	},

	//绑定点击事件
	bindEventFunction:function(){

	},
	//插入管理选项
	insertManageFunction:function(){

	},

	parseData:function(xmlhttp){
		var dataNode=xmlhttp.responseXML.getElementsByTagName("data");
		var nodeName=dataNode[0].getAttribute("name");
		this.name=nodeName;
		//考虑分页的情况
		var total=dataNode[0].getAttribute("total");

		if(total){
			this.total=parseInt(total);
            if(document.getElementById("highslide-comments-number"))
                document.getElementById("highslide-comments-number").innerHTML=this.total;
        }

        if( this.hs_pager ) this.changeHsPager();

		var perPage=dataNode[0].getAttribute("perpage");
		if(perPage)
			this.perPage=parseInt(perPage);
		var data=[];
		var nodes=xmlhttp.responseXML.getElementsByTagName(nodeName);

		if(nodes){
			var da=[];
			for(var i=0;i<nodes.length;i++){
				var node=nodes[i];
				var cnodes=node.childNodes;
				var d=[];
				for(var j=0;j<cnodes.length;j++){
					var name=cnodes[j].tagName;
					if(cnodes[j].firstChild)
						var value=cnodes[j].firstChild.data;
					else
						var value="";
					d[name]=value;

				}
				//var icon=nodes[i].childNodes[5].firstChild.data;
				da[da.length]=d;
				//if(d.id)
				//	da[d.id]=d;
			}
			data[nodeName]=da;
		}
		this.data=data;
	},
	_post: function(method, callback, params, postBody) {
    	var url = this.END_POINT;
    	var query = this._queryString(method, params);
    	this.ajax=new Ajax.Request(url, { parameters:     query,
                         postBody:       postBody,
                         method:         "post",
                         methodName:     method,
                         onComplete:     callback });
   },
   _queryString: function(method, params) {
    	var query = 'op=' + method;
    	if (this.session_id&&this.needSession)
      		query += '&session_id=' + this.session_id;
    	for (var name in params) {
      		if (name != 'extend')
        		if (params[name]) {
          			query += '&' + name + '=' + params[name];
        		}
    	}
    return query;
   },
   onLoadFunction:function(xmlhttp){

   		if (xmlhttp.status != 200)
        {
            //状态提示
            return new Array();
        }
        var elements = xmlhttp.responseXML.getElementsByTagName("rsp");
        if (elements == null || elements.length != 1)
        {
            return new Array();
        }
        var status=new Array();
        var rsp = elements[0];
        var stat = rsp.getAttribute("stat");
        if(stat=="ok"){
        	this.parseData(xmlhttp);

        	this.renderFunction();
        	if(this.bindEventFunction)
        		this.bindEventFunction();
        	if(typeof(is_config)!="undefined")
				return;


        	//this.options.bindFunc();
        }
	    else{
	    	var err = rsp.firstChild;
            var errorCode = err.getAttribute("code");
            var errorMsg = err.getAttribute("msg");
            alert(errorMsg);
	    }

   }
});

Pager=BaseModule.extend({
	initialize:function(){
		this.parent();
		/*this.setOptions({
			bindFunc:this.bindEventFunction.bind(this)

		});*/
		this.CACHE=[];
		this.loading=true;
		this.currentPage=1;
		this.total=0;
		this.showPage=true;
		this.cacheKey="";
	},
	loadFunction:function(e){
		//如果是点击某页
		if(window.isOwner&&!window.modManageCreated[this.id]){
			this.insertManageFunction();
			window.modManageCreated[this.id]=true;
			this.manageCreated=true;
		}
		if(e){
			var element=Event.element(e);
			if(!element)
				return;

			if(!element.tagName)
				element=element.parentNode;
			var id=element.id;
			id=id.substring(6);
			//页数id为pager_,因此截取6
			var pId=parseInt(id);
			//如果是当前页的话返回
			if(this.currentPage==pId)
				return;
			//如果有缓存的话
			this.currentPage=pId;
			if(this.CACHE[id]){
				$(this.contentId).innerHTML=this.CACHE[id];
				this.initPager();
			}else{
				this.params["page"]=pId;
				$(this.contentId).innerHTML="正在加载数据中";
				this._post(this.op,this.onLoadFunction.bind(this),this.params);
			}

		}else if(this.CACHE[this.currentPage+""]){
			$(this.contentId).innerHTML=this.CACHE[this.currentPage+""];
			this.initPager();
		}
		else{
			this._post(this.op,this.onLoadFunction.bind(this),this.params);
		}

	},

	bindEventFunction:function(){
		if(this.total>0&&this.showPage){
			this.CACHE[this.cacheKey+this.currentPage]=$(this.contentId).innerHTML;
			this.initPager();
		}
	},
	initPager:function(){
		if(!this.showPage)
			return;
		if(this.total<this.perPage){
			return;
		}
		if(this.total%this.perPage==0)
			var totalPages=this.total/this.perPage;
		else
			var totalPages=parseInt(this.total/this.perPage)+1;
		var perPage=this.perPage;
		var totalLinks=10;
		var total=this.total;
		var currentPage=parseInt(this.currentPage);
		this.totalPages=totalPages;
    //{* totalLinks是总的显示页码数。如果没有指定，则缺省显示10个页码的链接 *}
	var html="";
    //{* 如果总页数小于10，直接显示 *}
    if(totalPages<=totalLinks){
    	for(var i=1;i<=totalPages;i++){
    		if(i==currentPage)
    			html+='<span class="pagerCurrent">'+i+'</span>';
    		else
    			//html+='<a class="pagerLinks" href="#comments"><span id="comments_page_'+i+'">'+i+'</span></a>';
    			html+='<a class="pagerLinks" href="#'+this.id+'" id="pager_'+i+'">'+i+'</a>';
    	}
    }
    // {* 总页数 〉１０　*}
    else{
    	if(currentPage<5){
    		var counter=0;
    		for(var i=1;i<=totalPages;i++){
    			if(i<7||i>(totalPages-2)){
    			  if(i==currentPage)
    			    html+='<span class="pagerCurrent">'+i+'</span>';
    			  else
    			    //html+='<a class="pagerLinks" href="#comments"><span id="comments_page_'+i+'">'+i+'</span></a>';
    			    html+='<a class="pagerLinks" href="#'+this.id+'" id="pager_'+i+'">'+i+'</a>';
    			  }
    			  else if(counter==0){
    			  	counter++;
    			  	html+="<span>...</span>";
    			  }

    		}//end for
		}//end <5
		else if(currentPage>totalPages-5){
		  var counter1=0;
          for(var i=1;i<=totalPages;i++){
            if(i<3||(i>(currentPage-3)&&i>totalPages-7)){
              if(i==currentPage)
                 html+='<span class="pagerCurrent">'+i+'</span>';
              else
                 //html+='<a class="pagerLinks" href="#comments"><span id="comments_page_'+i+'">'+i+'</span></a>';
                 html+='<a class="pagerLinks" href="#'+this.id+'" id="pager_'+i+'">'+i+'</a>';
            }
            else if(counter1==0){
              counter1++;
    		  html+="<span>...</span>";
            }//end if
          }//end for
		}//end else if
		else if(currentPage>=5 &&currentPage<=totalPages-5){
		  var counter2=0;
		  var counter3=0;
		  for(var i=1;i<=totalPages;i++){
		    if(i<3||(i>currentPage-4&&i<currentPage+4)||i>totalPages-2){
		      if(i==currentPage)
                 html+='<span class="pagerCurrent">'+i+'</span>';
              else
                 //html+='<a class="pagerLinks" href="#comments"><span id="comments_page_'+i+'">'+i+'</span></a>';
                 html+='<a class="pagerLinks" href="#'+this.id+'" id="pager_'+i+'">'+i+'</a>';
		    }//end if
		    else{
		      if(i>=3&&i<=currentPage-4&&counter2==0){
		        counter2++;html+="<span>...</span>";
		      }
		      else if(i>=currentPage+4&&i<=(totalPages-3)&&counter3==0){
		        counter3++;html+='<span>...</span>';
		      }
		    }//end else
		  }//end for
		}//end else if
    }
    html+='<span id="desc">(共'+total+'条记录)</span>';
    //$(this.pagerId).style.display="";
    var div=document.createElement("div");
    div.className="pager";
    div.innerHTML=html;
    $(this.contentId).appendChild(div);
    //绑定onclick事件,下面的处理方式不合适
    var elements=document.getElementsByClassName("pagerLinks");
    for(var i=0;i<elements.length;i++)
    	elements[i].onclick=this.loadFunction.bindAsEventListener(this);
    this.loading=false;

	}
});
HighslideCommentsMod=BaseModule.extend({
	initialize:function(params){
		this.parent();
        this.init(params);
		this.params=params;
        //{res_type:res_type,user_id:window.user_id,res_id:window.res_id,total:this.total,perpage:this.perPage};
        var cache_id=(params.res_id&&params.res_type)?"hs_"+params.res_type+"_"+params.res_id:false;
        this.perPage = (typeof(this.params.perPage)!="undefined")?this.params.perPage:10;
        this.hs_pager=true;
        this.total=0;
        this.loadFunction(this,{cache_id:cache_id});
        this.bindHsPager();
    },
    init:function(){
		this.id="comments";
		this.contentId="comments_list";
		this.jstId="highslideCommentsJST";

		this.op="bloghome.operate.getComments";

	    $("addCommentBtn").onclick=this.addComment.bindAsEventListener(this);
        this.dynamicCreateJstTemplate();
	},
    dynamicCreateJstTemplate:function(){
        var div=document.createElement("div");
        div.style.display="none";
        div.innerHTML=''
                +'<textarea name="name" id="highslideCommentsJST" style="display:none">'
                    +'{for p in comment}<table width=262 border=0><tr><td valign=top align=left>'
                        +'<div class="icon">{if p.url.length>0} <a href="${p.url}" title="访问${p.fullname}的主页" class="login-comment"><img src="${p.icon}" onmouseover="this.style.height=60;this.style.width=60;" onmouseout="this.style.height=20;this.style.width=20;"/></a> {else} <img src="${p.icon}" onmouseover="this.style.height=60;this.style.width=60;" onmouseout="this.style.height=20;this.style.width=20;"> {/if}</div>'
                        +'<div><p class="name">{if p.url.length>0} <a href="${p.url}" class="">${p.fullname}</a>  {else} ${p. fullname} {/if}&nbsp;&nbsp;${p.date}：</p></div><br clear="all"/><div style="content">${p.text}</div>'
                    +'</td></tr></table>{forelse} 目前还没有评论。{/for}'
                +'</textarea>';
        document.body.appendChild(div);
    },
    bindHsPager:function(){
        $("hs_page_e").onchange=this.loadFunction.bind(this);
    },
    changeHsPager:function(){
        $("hs_page_e").innerHTML="";//appendChild(option);

        // 是否显示hs的pager
        if( this.total>0 ){
            var len=(this.total%this.perPage)?(this.total/this.perPage+1):(this.total/this.perPage);
            for( var i=1; i<=len; i++ ){
                var option = document.createElement("OPTION");
                option.value=i;
                option.innerHTML = i+" / "+this.total;
                $("hs_page_e").appendChild(option);
            }
            if( typeof(this.currentPage) =="undefined" ) this.currentPage=1;
            $("hs_page_e").selectedIndex=this.currentPage-1;
        }
        if( this.total== 0 ) {
            var option = document.createElement("OPTION");
            option.value=1;
            option.innerHTML = 0+" / "+this.total;
            $("hs_page_e").appendChild(option);
        }
    },
    addComment:function(){
		//alert("add")
		var res_id=window.res_id;
	 	var text=window.content.body.innerHTML;

	 	var tmpText=text.trim();
	 	tmpText=tmpText.replace("&nbsp;","");
	 	tmpText=tmpText.replace("<br>","");
	 	if(tmpText.trim().length<1){
	 		alert("请输入回复内容，至少1个字");
	 		return false;
	 	}
	 	text = encodeURIComponent(text);
	 	var username=$("commentUserName").value;
	 	//增加验证判断
	 	if(username.trim().length<2){
	 		alert("请输入用户名");
	 		return false;
	 	}
        var params={
                res_id:this.params.res_id,
                text:text,
                username:username,
                res_type:this.params.res_type,
                user_id:window.user_id
        };
	 	this._post("bloghome.operate.addComment",this.onAddComment.bind(this),params);
	},
	onAddComment:function(xmlhttp){
        //状态提示
		if (xmlhttp.status != 200) {  return new Array(); }
        var elements = xmlhttp.responseXML.getElementsByTagName("rsp");
        if (elements == null || elements.length != 1) { return new Array(); }
        var status=new Array();
        var rsp = elements[0];
        var stat = rsp.getAttribute("stat");
        if(stat=="ok"){
        	this.parseData(xmlhttp);
        	this.createCommentUI();
            if(document.getElementById("highslide-comments-number"))
                document.getElementById("highslide-comments-number").innerHTML=this.total;
	 	    content.body.innerHTML="";
            this.changeHsPager();
        }
	    else{
	    	var err = rsp.firstChild;
            var errorCode = err.getAttribute("code");
            var errorMsg = err.getAttribute("msg");
            alert(errorMsg);
	    }
	},
	createCommentUI:function(){
		this.data._MODIFIERS=TT_Filters;
		var result = TrimPath.processDOMTemplate(this.jstId, this.data);

		if(this.total===0){
			$(this.contentId).innerHTML=result;
			this.total=1;
		}else{
			this.total++;
            new Insertion.Top(this.contentId,result);
		}
	}
});
//var CommentsMod=Class.create();
CommentsMod=Pager.extend({
	initialize:function(){
		this.parent()
		this.init();
		if(typeof(commentsList)=='undefined'){
            if(res_type==1 && typeof(shop_article)=='undefined')
                return;
			this.jumpCommentsList=false;
			this.loadFunction();
		}
		else
			this.jumpCommentsList=true;
	},
	init:function(){
		this.perPage=10;
		this.id="comments";
		this.contentId="commentsContent";
		this.jstId="commentsJST";

		this.op="bloghome.operate.getComments";

		this.params={res_type:res_type,user_id:window.user_id,res_id:window.res_id,total:this.total,perpage:this.perPage};

	    //处理form
	    if(window.visitor_name){
	  	  $("commentUserName").value=window.visitor_name;
	    }
	    $("addCommentBtn").onclick=this.addComment.bindAsEventListener(this);
	    $("resetCommentBtn").onclick=this.reset.bindAsEventListener(this);
        $$("#comments .reply-comment-user").forEach(function(al){al.onclick=this.replyCommentUser.pass(al.id).bindAsEventListener(this);},this);
	},
    replyCommentUser:function(s_id){
        var cancelReplyCommentUser=function(){
            $('reply-comment-user-tip').parentNode.removeChild($('reply-comment-user-tip'));
            $('reply-comment-user-tip-cancelBtn').parentNode.removeChild($('reply-comment-user-tip-cancelBtn'));
            $('reply-comment-user-id').value=null;
            $('reply-comment-user-level').value=null;
            $('reply-comment-user-comment-id').value=null;
        }
        window.anchorScroller( 'commentForm', 1000 );
        var a = s_id.split( "_" ), commentId=a[1],level=a[2], rcuId=a[3];
        $('reply-comment-user-id').value=rcuId;
        $('reply-comment-user-level').value=level;
        $('reply-comment-user-comment-id').value=commentId;
        if( !$('reply-comment-user-tip') ){
            var span= document.createElement( 'span' );
            var cancelBtn= document.createElement( 'button' );
            with(cancelBtn){
                innerHTML='取消';
                id='reply-comment-user-tip-cancelBtn';
                className='reply-comment-user-tip-cancelBtn';
            }
            with(span){
                id='reply-comment-user-tip';
                className='reply-comment-user-tip';
            }
            $('commentUserName').parentNode.appendChild(span);
            $('commentUserName').parentNode.appendChild(cancelBtn);
            cancelBtn.onclick=cancelReplyCommentUser;
        }
        $('reply-comment-user-tip').innerHTML='回第'+level+'楼'; 
    },
	addComment:function(){
		//alert("add")
		var res_id=window.res_id;
	 	//var topic=$("commentTopic").value;
	 	//topic = encodeURIComponent(topic);
	 	var text=content.body.innerHTML;

	 	var tmpText=text.trim();
	 	tmpText=tmpText.replace("&nbsp;","");
	 	tmpText=tmpText.replace("<br>","");
	 	if(tmpText.trim().length<1){
	 		alert("请输入回复内容，至少1个字");
	 		return false;
	 	}
	 	text = encodeURIComponent(text);
	 	var username=$("commentUserName").value;
	 	//增加验证判断
	 	if(username.trim().length<2){
	 		alert("请输入用户名");
	 		return false;
	 	}
        if($("comment_form"))
	 	    $("comment_form").style.display="none";
	 	$("tipAddComments").style.display="block";
         
        var rcui=$('reply-comment-user-id').value;
        var rcul=$('reply-comment-user-level').value;
        var rcuci=$('reply-comment-user-comment-id').value;
	 	var params={res_id:res_id,text:text,username:username,res_type:window.res_type,user_id:window.user_id,'reply-comment-user-id':rcui,'reply-comment-user-level':rcul,'reply-comment-user-comment-id':rcuci};
	 	this._post("bloghome.operate.addComment",this.onAddComment.bind(this),params);
	},
	//清空回复框的内容
	reset:function(){
		content.body.innerHTML="";
		$("commentTopic").value="";
	},
	onAddComment:function(xmlhttp){
		if (xmlhttp.status != 200)
        {
            //状态提示
            return new Array();
        }
        var elements = xmlhttp.responseXML.getElementsByTagName("rsp");
        if (elements == null || elements.length != 1)
        {
            return new Array();
        }
        var status=new Array();
        var rsp = elements[0];
        var stat = rsp.getAttribute("stat");
        var total=rsp.getAttribute("total");
        if(stat=="ok"){
        	if(res_type==1 && typeof(shop_article)=='undefined'){
                total=parseInt(total);
                if(total%this.perPage==0)
                    totalPages=total/this.perPage;
                else
                    totalPages=parseInt(total/this.perPage)+1;
                if(totalPages==1)
                	totalPages="index";
				var date=new Date();
        		window.location.href='/posts/comments/'+res_id+'/'+totalPages+'.html?d='+date.getTime();
        		return;
        	}
        	this.parseData(xmlhttp);
        	this.createCommentUI();
        }
	    else{
	    	var err = rsp.firstChild;
            var errorCode = err.getAttribute("code");

            var errorMsg = err.getAttribute("msg");

			if(errorCode=="111"){//如果是未登录用户

				if(!window.qLogin){
					window.qLogin=new QuickLogin();
					qLogin.show();
					qLogin.bindFunc(this.quickLogin.bind(this));

				}


			}else if( errorCode == '110' ){
                alert( errorMsg );
            }
	    }
        if($("comment_form"))
		    $("comment_form").style.display="block";
	 	$("tipAddComments").style.display="none";

	},
    quickLogin:function(params){
		$("commentUserName").value=params["userName"];
		if(!(typeof(user_id)!="undefined"&&parseInt(user_id)<0))
			window.user_id=params["userId"];

		this.addComment();

	},
	createCommentUI:function(){
		this.data._MODIFIERS=TT_Filters;
		var result = TrimPath.processDOMTemplate(this.jstId, this.data);
		if(this.total==0){
			$(this.contentId).innerHTML=result;
			this.total=1;
		}else{
			this.total++;
			if(this.total>this.perPage){
				if(this.total%this.perPage==0)
					var totalPages=this.total/this.perPage;
				else
					var totalPages=parseInt(this.total/this.perPage)+1;
				//清空cache
				this.currentPage=totalPages;
				this.CACHE=[];
				$(this.contentId).innerHTML="正在加载数据..";
				this.params["page"]=this.currentPage;

				this.loadFunction();
				return false;
			}
			var page=$$("#comments .pager");

			if(page&&page.length>0){
				new Insertion.Before(page[0],result);
				var desc=page[0].getLast();
				desc.innerHTML='(共'+this.total+'条回复';
			}
			else
				new Insertion.Bottom(this.contentId,result);
		}
	}
});
String.prototype.trim = function() {
  var s = this;
  while (s.substring(0,1) == ' ') {
    s = s.substring(1,s.length);
  }
  while (s.substring(s.length-1,s.length) == ' ') {
    s = s.substring(0,s.length-1);
  }
  return s;
}
