var mozilla = (navigator.userAgent.toLowerCase().indexOf("msie") == -1);
var ArticleNote=Class.create();
var minWords=1;
var maxWords=50;
var maxContentLength=500;
ArticleNote.prototype =
{
    initialize: function()
    {
    	if(!enable_note)
    		return;	
		this.END_POINT = '/blogcontrol.php';
    	this.session_id=window.session_id;
    	if(typeof(visitor_id)!="undefined"){
			$("article_main").onmouseup= this.onSelect.bindAsEventListener(this);
			$("article_main").onmousedown= this.onMouseDown.bindAsEventListener(this);
		}
		this.CACHE=new Array();
		this.CACHE["notes"]=new Array();
		this.CACHE["loaded"]=new Array();
		this.CACHE["total"]=new Array();
		this.currentNoteId=false;
		this.init();
	},
	init:function(){
		var elements=document.getElementsByClassName("noted");
		if(elements){
			for(i=0;i<elements.length;i++){
				elements[i].onmouseover=this.showNotes.bindAsEventListener(this);
					
			}	
		}
		if(!this.htmlElement)
			this.createUI();
	},
	createUI:function(){
		var div=document.createElement("div");
		div.id="textFrame";
		div.style.display="none";

		var html='<div class="closeFrame"><a href="javascript:;" id="close_note_win"><img src="/imgs/blog/notes/close.gif"></a></div>';
		html+='<div class="frameArrow"></div>';
		html+='<div class="frameMain">';
		html+='<div class="frameTop"></div>';
		
		html+='<h2 class="frameTitle">对<span id="note_key"></span>的评注</h2>';
		html+='<div align="left"><span class="control"><a href="javascript:;" id="add_new_note">添加新的评注</a><a href="javascript:;" id="note_help_btn">帮助</a></span></div>';
		html+='<div class="inFrame">';
		html+='<div class="inFrameTop"></div>';
		html+='<div class="inFrameMain">';
		html+='<div id="notes_list"></div>';
		html+='<form action="" method="post" name="" id="add_note_form" style="display:none">';
		html+='<textarea class="framePost" id="note_text" onfocus="this.select()">请输入您的评注内容，字数不能多于'+maxContentLength+'</textarea>';
		html+='<input type="button" class="frameButton" name="" value="添加评注" id="add_note_btn" >';
		html+='<input type="button" class="frameButton" name="" value="取消" id="cancel_add_note_btn" >';
		html+='</form>';
		html+='<div id="notes_help" style="display:none">';
		html+='<p><strong>如何添加评注</strong><br>1:首先在文章正文区域用鼠标选择文字('+minWords+'-'+maxWords+'字)<br>2:这时文字左上方会出现这个图标:<img src="/imgs/blog/notes/bz.gif">';
		html+='点击图标.<br>3:这时会出现添加评注的界面,输入你要评注的内容,点击添加评注即可.<br>4:你也可以对别人已经评注的文字再次评注,方法是鼠标移到评注的文字上后出现别人已经评注的内容';
		html+=',点击上方的那个添加评注,可以继续对已经评注的文字添加评注.<br><input type="button" class="frameButton" name="" value="返回" id="cancel_note_help_btn" ></p></div>';
		html+='</div>';
		html+='<div class="inFrameBottom"></div>';
		html+='</div>';
		
		html+='<div class="frameBottom"></div>';
		html+='</div>';
		div.innerHTML=html;
		document.body.appendChild(div);
		this.htmlElement=div;
		$("close_note_win").onclick=this.hide.bindAsEventListener(this);
		$("add_new_note").onclick=this.showAddNote.bindAsEventListener(this);
		$("add_note_btn").onclick=this.addNote.bindAsEventListener(this);
		$("cancel_add_note_btn").onclick=this.cancelAddNote.bindAsEventListener(this);
		$("note_help_btn").onclick=this.showNoteHelp.bindAsEventListener(this);
		$("cancel_note_help_btn").onclick=this.cancelAddNote.bindAsEventListener(this);
	},
	hide:function(e){
		this.htmlElement.style.display="none";
		$("notes_list").innerHTML="正在加载评注";
		$("notes_help").style.display="none";
		this.currentNoteId=false;
		this.showWin=false;
		if(this.icon)
			this.icon.style.display="none";
		this.removeSelected();
	},
	removeSelected:function(){
		if(this.selectedElement){	
			var text=this.selectedElement.innerHTML;
			var textNode=document.createTextNode(text);
			this.selectedElement.parentNode.replaceChild(textNode,this.selectedElement);
			this.selectedElement=false;
		}
	
	},
	showAddNote:function(e){
		$("notes_help").style.display="none";
		$("notes_list").style.display="none";
		$("add_note_form").style.display="";
		$("note_text").value="请输入您要评注的内容，字数不能多于"+maxContentLength;
	},
	addNote:function(e){
		var text=$("note_text").value;
		note_id=this.currentNoteId;
		if(!note_id)
			note_id=0
		this._addNote(note_id,res_id,text,this.onAddNote.bind(this));
	},
	cancelAddNote:function(e){
		$("add_note_form").style.display="none";
		$("notes_help").style.display="none";
		this.currentPage=1;
		this.htmlElement.style.display="";
		$("notes_list").style.display="";
		$("notes_list").innerHTML="正在载入评注";
		if(this.CACHE["notes"][this.currentNoteId+"_"+this.currentPage]){
			$("notes_list").innerHTML=this.CACHE["notes"][this.currentNoteId+"_"+this.currentPage];
			this.initPageEvent();
		}
		else
			this._getNotes(this.currentNoteId,1,this.onGetNotes.bind(this));
	
	},
	showNoteHelp:function(){
		$("notes_list").style.display="none";
		$("add_note_form").style.display="none";
		$("notes_help").style.display="";
	
	},
	showNotes:function(e){
		this.removeSelected();
		if(!mozilla){
			selectRange=document.selection.createRange();
			
			text=selectRange.text;
			if(text.length>0)
				return;
		}
		else{
			selectRange=window.getSelection();
			text=selectRange.toString();
			if(text.length>0)
				return;
		}
		$("notes_help").style.display="none";
		var element=Event.element(e);
		var text=element.innerHTML;
		if(!element.id)
			return;
		var id=element.id.substring(5);
		id=parseInt(id);
		if(!id)
			return;
		this.currentNoteId=id;
		$("add_note_form").style.display="none";
		this.currentPage=1;
		this.htmlElement.style.display="";
		$("notes_list").innerHTML="正在载入评注";
		$("note_key").innerHTML=text;
		this.positionWin(e);
		if(this.CACHE["notes"][id+"_"+this.currentPage]){
			$("notes_list").innerHTML=this.CACHE["notes"][id+"_"+this.currentPage];
			this.initPageEvent();
		}
		else
			this._getNotes(this.currentNoteId,1,this.onGetNotes.bind(this));
	},
	initPageEvent:function(){
		var elements=document.getElementsByClassName("notes_pager");
		if(elements){
			for(i=0;i<elements.length;i++)
				elements[i].onclick=this.showPagerNotes.bindAsEventListener(this);
		}
		$("notes_pager_"+this.currentPage).className="pagers_current";
		
	},
	showPagerNotes:function(e){
		$("notes_help").style.display="none";
		var element=Event.element(e);
		var id=element.id.substring(12);
		this.currentPage=id;
		if(this.CACHE["notes"][this.currentNoteId+"_"+this.currentPage]){
			$("notes_list").innerHTML=this.CACHE["notes"][this.currentNoteId+"_"+this.currentPage];
			this.initPageEvent();
		}
		else
			this._getNotes(this.currentNoteId,this.currentPage,this.onGetNotes.bind(this));
	},
    onMouseDown:function(e)
    {
		 this.deltaX =  window.pageXOffset
                || document.documentElement.scrollLeft
                || document.body.scrollLeft
                || 0;
		this.deltaY =  window.pageYOffset
                || document.documentElement.scrollTop
                || document.body.scrollTop
                || 0;
        this.x= e.clientX+ this.deltaX ;
		this.y= e.clientY+ this.deltaY ;
		
	},
	onSelect:function(e)
	{

			 this.deltaX =  window.pageXOffset
                || document.documentElement.scrollLeft
                || document.body.scrollLeft
                || 0;
			this.deltaY =  window.pageYOffset
                || document.documentElement.scrollTop
                || document.body.scrollTop
                || 0;
			this.x2= e.clientX+ this.deltaX ;
			this.y2= e.clientY+ this.deltaY ;
			
			var selectRange=false;
			var selectParent=false;
			var text;
			if(!mozilla){
				selectRange=document.selection.createRange();
				if(!selectRange)
					return;
				selectParent=selectRange.parentElement();
				text=selectRange.text;
				
			}else{
				selectRange=window.getSelection();
				if(!selectRange)
					return;
				selectParent=selectRange.focusNode.parentNode;
				text=selectRange.toString();
				
			}
			
			if(!(text.length>minWords)||!(text.length<maxWords))
				return;
			
			if(selectParent.className=="noted")
				return;	
			if(this.search(text)){
				this.showAddNoteIcon();
				var elements=document.getElementsByClassName("noted");
				if(elements){
					for(i=0;i<elements.length;i++){
						if(elements[i]!=this.selectedElement)
							elements[i].onmouseover=this.showNotes.bindAsEventListener(this);
					
					}	
				}	
			}	
	},
	search:function(strSearch)
    {
		var node=$("article_main");
		var strHTML=node.innerHTML;
		var htmlArray=new Array();
		iPos = strHTML.search(strSearch);
		if(iPos<=0)
				return false;
		while(iPos>0){
			str1 = (strHTML.substring(0, iPos));
			str2 = "<span class='checked'>" +strHTML.substring(iPos,strSearch.length+iPos)+"</span>";
			str3 = (strHTML.substring(strSearch.length+iPos));
			htmlArray[htmlArray.length]=str1;
			htmlArray[htmlArray.length]=str2;
			strHTML=str3;
			iPos=strHTML.search(strSearch);
		}
		
		var html="";
		for (i=0;i<htmlArray.length;i++ )
		{
			html+=htmlArray[i];
		}
		html+=strHTML;
		node.innerHTML=html;
		var elements=document.getElementsByClassName("checked");
		if(elements){
			var selectedElement=false;
			var offset=100;
			for(i=0;i<elements.length;i++){
					var element=elements[i];
					var off=this.countOffset(element);
					if(off<offset){
						selectedElement=element;
						offset=off;
					}

			}//end for
			selectedElement.className="noted";
			selectedElement.id="note_temp";
			this.selectedElement=selectedElement;
			for(i=0;i<elements.length;i++){
				var element=elements[i];
				if(element!=selectedElement){
					var textNode=document.createTextNode(strSearch);
					element.parentNode.replaceChild(textNode,element);

				}

			}
			new Insertion.Before("note_temp",'<span id="span_tmp"></span>');
			var html=$("article_main").innerHTML.toLowerCase();
			
			var position=html.indexOf('<span id="span_tmp"></span>');
			if(position==-1)
				position=html.indexOf('<span id=span_tmp></span>');
			$("span_tmp").parentNode.removeChild($("span_tmp"));
			this.position=position;
		}
		if(mozilla){
			sel = window.getSelection();
			sel.removeAllRanges();
		}
		
		return true;
	},
    showAddNoteIcon:function(){
		if(!this.icon){
			var div=document.createElement("div");
			with(div.style){
				position="absolute";
				height="14px";
				width="14px";
				display="none";
				background="#fff";
			}
			div.innerHTML="<img src='/imgs/blog/notes/bz.gif'>";
			document.body.appendChild(div);
			this.icon=div;
		}
		this.positionIcon();
		this.icon.onmouseover=this.onIconMouseOver.bindAsEventListener(this);
		this.icon.onmouseout=this.onIconMouseOut.bindAsEventListener(this);

		setTimeout(this.hideIcon.bind(this),2000);
		this.icon.onclick=this.showAddNoteWin.bindAsEventListener(this);
		this.htmlElement.style.display="none";
	},
    showAddNoteWin:function(e){
		this.positionWin(e);
		$("notes_list").style.display="none";
		$("add_note_form").style.display="";
		this.currentNoteId=false;
		this.showWin=true;
		var text=this.selectedElement.innerHTML;
		$("note_key").innerHTML=text;
		$("note_text").value="请输入您的评注内容";
	},
    
	onIconMouseOver:function(e){
		this.iconOver=true;
		setTimeout(this.hideIcon.bind(this),2000);	
	},
	onIconMouseOut:function(e){
		this.iconOver=false;
	},
	hideIcon:function(e){
		if(!this.iconOver){			
			this.icon.style.display="none";
		}
		if(!this.iconOver&&!this.showWin&&this.selectedElement){
			this.removeSelected();
		}

	},
    positionIcon:function(){
		var x=this.x;
		if(x<this.x2)
			x=this.x2;
		this.selectedElement.style.position="absolute";	
		var pos=Position.cumulativeOffset(this.selectedElement);
		//this.selectedElement.style.position="static";
		this.selectedElement.removeAttribute("style");
		y=pos[1];
		y=y-this.selectedElement.offsetHeight-5;
		
		this.icon.style.left=x+"px";
		this.icon.style.top=y+"px";
		this.icon.style.display="";
	},
	positionWin:function(e){
	
		if (this.htmlElement)
        {
             this.deltaX =  window.pageXOffset
                || document.documentElement.scrollLeft
                || document.body.scrollLeft
                || 0;
    		this.deltaY =  window.pageYOffset
                || document.documentElement.scrollTop
                || document.body.scrollTop
                || 0;
            var element=Event.element(e);
            element.style.position="absolute";
            var pos=Position.cumulativeOffset(element);
            element.removeAttribute("style");
            var x=pos[0]+element.offsetWidth;
            var y= pos[1]-80;
            if(!mozilla&&element.className&&element.className=="noted"){
            }
            this.htmlElement.style.left = x+83 + "px";
            this.htmlElement.style.top = y + "px";
            this.htmlElement.style.display="";
        }
        $("notes_help").style.display="none";
	},
    getNotes:function(e){
		var element=Event.element(e);
		var id=element.id;
		id=id.subtring(5);


	},
	countOffset:function(element){
		element.style.position="absolute";
		var pos=Position.cumulativeOffset(element);
		element.style.position="static";
		element.removeAttribute("style");
		var x=this.x;
		var y=this.y;
		if(this.x2<x)
			x=this.x2;
		offset=Math.abs(pos[0]-x)+Math.abs(this.y-pos[1]);
		return offset;

	},
	_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)
      		query += '&session_id=' + this.session_id;
    	for (var name in params) {
      		if (name != 'extend')
        		if (params[name]) {
          			query += '&' + name + '=' + params[name];
        		}
    	}
    return query;
  },
  _getNotes:function(note_id,page,callback){
		this._post('yakbo.blog.getNotes', callback, {note_id:note_id,page:page});		
  },
  _addNote:function(note_id,article_id,text,callback){
  		if(text.length>maxContentLength){
  			alert("评注字数不能多于"+maxContentLength);
  			return false;
  		}
  		if(!note_id){
  			var note_text=this.selectedElement.innerHTML;

  			this._post('yakbo.blog.addNote', callback, {position:this.position,article_id:article_id,text:text,note_text:note_text});
  			
  		}
  		else{
  			note_id=parseInt(note_id);
			this._post('yakbo.blog.addNote', callback, {note_id:note_id,article_id:article_id,text:text});
		}	
  },

  onAddNote:function(xmlhttp){
  		if (xmlhttp.status != 200)
        {
            return ;
        }
        var elements = xmlhttp.responseXML.getElementsByTagName("rsp");
        if (elements == null || elements.length != 1)
        {
            return ;
        }

        var rsp = elements[0];

        var stat = rsp.getAttribute("stat");
        if (stat == "ok")
        {
			var note_id=rsp.childNodes[0].firstChild.data;
			var text=rsp.childNodes[1].firstChild.data;
			if(!this.currentNoteId){
				this.currentNoteId=note_id;
			}
			if(this.CACHE["loaded"]["l"+note_id]){
				if(this.CACHE["total"]["t"+note_id]){
					var n=this.CACHE["total"]["t"+note_id];
					n=n+1;
					this.CACHE["total"]["t"+note_id]=n;
					if(n%5==0)
						pages=n/5;
					else
						pages=parseInt(n/5)+1;
					for(i=1;i<=pages;i++){
						this.CACHE["notes"][note_id+"_"+i]=false;					
					}
				}
			}
			
			$("add_note_form").style.display="none";
			$("notes_list").innerHTML="添加成功";
			this.currentPage=1;
			this._getNotes(note_id,1,this.onGetNotes.bind(this));
			if(this.selectedElement){
				this.selectedElement.id="note_"+note_id;				
				this.selectedElement=false;
				this.init();
			}
        }
        else
        {
            var err = rsp.firstChild;
            var errorCode = err.getAttribute("code");
            var errorMsg = err.getAttribute("msg");
            alert(errorMsg);
        }
  },
  onGetNotes:function(xmlhttp){
  		if (xmlhttp.status != 200)
        {
            return ;
        }
        var elements = xmlhttp.responseXML.getElementsByTagName("rsp");
        if (elements == null || elements.length != 1)
        {
            return ;
        }

        var rsp = elements[0];

        var stat = rsp.getAttribute("stat");
        if (stat == "ok")
        {
        	var total=rsp.getAttribute("total");
        	var elements = xmlhttp.responseXML.getElementsByTagName("note");
        	var html='<ul class="list">';
        	for(i=0;i<elements.length;i++){
        		var element=elements[i];
				var user=element.childNodes[0].firstChild.data;
				var url=element.childNodes[1].firstChild.data;
				var date=element.childNodes[2].firstChild.data;
				var text=element.childNodes[3].firstChild.data;	
				html+='<li><a href="'+url+'" target="_blank">'+user+'</a>于<span class="notedate">'+date+'</span>评注：<br>';
				html+='<p>'+text+'</p></li>';		
			}
			html+='</ul>';
			if(total%5==0)
				pages=total/5;
			else
				pages=total/5+1;
			
			html+='<div class="pageCuter">';
			for(i=1;i<=pages;i++)
				html+='<a href="javascript:;" class="notes_pager" id="notes_pager_'+i+'">'+i+'</a>';
			html+='</div>';
			this.CACHE["loaded"]["l"+this.currentNoteId]=true;
			this.CACHE["total"]["t"+this.currentNoteId]=total;
			this.CACHE["notes"][this.currentNoteId+"_"+this.currentPage]=html;
			$("notes_list").innerHTML=html;
			$("notes_list").style.display="";
			this.initPageEvent();
        }
        else
        {
            var err = rsp.firstChild;
            var errorCode = err.getAttribute("code");
            var errorMsg = err.getAttribute("msg");
            alert(errorMsg);
        }
  
  
  
  }
  

}


document.getElementsByClassName = function(className) {
  var children = document.getElementsByTagName('*') || document.all;
  var elements = new Array();
  
  for (var i = 0; i < children.length; i++) {
    var child = children[i];
    var classNames = child.className.split(' ');
    for (var j = 0; j < classNames.length; j++) {
      if (classNames[j] == className) {
        elements.push(child);
        break;
      }
    }
  }
  
  return elements;
}  

function getSel()
{
	var txt = '';
	var foundIn = '';
	if (window.getSelection)
	{
		txt = window.getSelection();		
	}
	else if (document.getSelection)
	{
		txt = document.getSelection();		
	}
	else if (document.selection)
	{
		txt = document.selection.createRange().text;
	}
	else return;
	return foundIn;
}
