/*
** 所有的Frame Pan 位置都是相对于body左上角的。
** 所有出去的leftToPic和topToPic都会减去picx, picy
** 所有进来的left和top都应该加上picx,picy
*/
var FRAME_W = 150, FRAME_H = 150, PAN_W = 150, PAN_H = 200, FRAME_MIN_W = 40, FRAME_MIN_H = 40, PHOTO_WIDTH = 600, M_MAX_X, M_MAX_Y, M_MIN_X, M_MIN_Y;
var SOLID_OUTER="5px solid #d8dfea", SOLID_INNER = "2px solid #005eac", DASHED_OUTER="7px solid #d8dfea", DASHED_INNER="2px solid #005eac";
var mousex=0, mousey=0;
var postResult = new Array();
var keyword="";
var tmpflist="";
function PhotoTag() {
	this.plugins = new Array();
	this.status = "";
	this.picId = "";
	this.frameId = "";
	this.frameWidth = FRAME_W;
	this.frameHeight = FRAME_H;
	this.leftToPic = 0;
	this.topToPic = 0;
	this.panWidth = PAN_W;
	this.picx = 0;
	this.picy = 0;
	this.picw = PHOTO_WIDTH;
	this.pich = 0;
	this.panHeight = PAN_H ;
	this.panId = "";
	this.drawPan_callback = "";
	this.mousex = 0;
	this.mousey = 0;
	this.mouseOffX = 0;
	this.mouseOffY = 0;
	this.direction = 0; 
	this.status = "normal_state";
	this.tagCount = 0;
 	this.tagList = new Array();
	this.pageloaded = false;
}
PhotoTag.prototype = {
	init: function(settings) {
		this.settings = settings;
		if(this.settings.picDivId != "") {
	  	this.picId = this.settings.picDivId;
		}
	  if(this.settings.frameId) {
			this.frameId = this.settings.frameId;
		} else {
		  this.frameId = "frameDiv"; 
		}
		if(this.settings.panId) {
			this.panId = this.settings.panId;
		} else {
			this.panId = "panDiv";
		}
	  if(this.settings.status) {
			this.status = this.settings.status;
		} else {
			this.status = "normal_state";
		}
	 	if(this.settings.drawPan_cb) {
			this.drawPan_callback = this.settings.drawPan_cb;
		}
	},
	albumMousePos: function(e,type) {
		//added by pekkyl for the max/min X/Y 
		mousex = mousePosX(e);
		mousey = mousePosY(e);
		this.picy = findPosY(this.pic);
		M_MIN_Y = photoTag.picy;
		M_MAX_Y = photoTag.picy + photoTag.pich;
		if(type == "center") {
			var maxX = M_MAX_X - photoTag.frameWidth/2;
			var minX = M_MIN_X + photoTag.frameWidth/2;
			var maxY = M_MAX_Y - photoTag.frameHeight/2;
			var minY = M_MIN_Y + photoTag.frameHeight/2;
		} else {
			var maxX = M_MAX_X;
			var minX = M_MIN_X;
			var maxY = M_MAX_Y;
			var minY = M_MIN_Y;
		}
		if(mousex > maxX) mousex = maxX;
		if(mousey > maxY) mousey = maxY;
		if(mousex < minX) mousex = minX;
		if(mousey < minY) mousey = minY;
		// end of Limit
	},
	setCursor: function(el,type) {
		el.style.cursor = type;	
	},
	initPageElement: function() {
		this.pic = this.getElement(this.picId,document.body);
		
		//this.pic = this.getElement(this.picId,document.body);
		//生成一个div和pic的大小一模一样，因为IE下不能实现image上的拖动。
		this.picx = findPosX(this.pic);
		this.picy = findPosY(this.pic);
		this.getPhotoDimension(this.pic);
		M_MIN_X = this.picx; 
		M_MIN_Y = this.picy;
		M_MAX_X = this.picx + this.picw;
		M_MAX_Y = this.picy + this.pich;
		this.frame = this.getElement(this.frameId,document.body);
		this.pan = this.getElement(this.panId,document.body);
		this.pan.style.display="none";
		 //实现回掉函数的方法，这里可以给函数传递参数，处理完了再传回来。
		var src,str = "数据读取中…";
		if(this.drawPan_callback) {
				src = eval(this.drawPan_callback + "('数据读取中…')");
		}
		this.drawPan(src);
		this.setElDimension(this.frame,this.frameWidth,this.frameHeight);
		//this.pic.ondrag = function() {return false};
		//this.frame.onclick = photoTag.setTag;
		this.inner = this.getElement("inner",this.frame);
		this.inner.onmouseover = this.inMoveArea; 	
		this.inner.onmouseout = this.outMoveArea;
		this.inner.onmousedown = this.beginMove;
		this.inner.onmouseup = this.endMove;
		var leftTop = this.getElement("leftTop",this.frame);	
		leftTop.onmouseover = this.inResizeArea; 	
		leftTop.onmouseout = this.outResizeArea;
		leftTop.onmousedown = this.beginResize;
		leftTop.onmouseup = this.endResize;
		var rightTop = this.getElement("rightTop",this.frame);	
		rightTop.onmouseover = this.inResizeArea; 	
		rightTop.onmouseout = this.outResizeArea;
		rightTop.onmousedown = this.beginResize;
		rightTop.onmouseup = this.endResize;
		var leftBottom = this.getElement("leftBottom",this.frame);	
		leftBottom.onmouseover = this.inResizeArea; 	
		leftBottom.onmouseout = this.outResizeArea;
		leftBottom.onmousedown = this.beginResize;
		leftBottom.onmouseup = this.endResize;
		var rightBottom = this.getElement("rightBottom",this.frame);	
		rightBottom.onmouseover = this.inResizeArea; 	
		rightBottom.onmouseout = this.outResizeArea;
		rightBottom.onmousedown = this.beginResize;
		rightBottom.onmouseup = this.endResize;
		this.pic.onmousedown = this.beginAction;
		this.pic.onmouseup = this.endResize;
		this.frame.onmousemove = this.resize;
		this.pic.onmouseover = this.refresh;
		this.pic.onmousemove = this.resize;
		this.pan.onmousemove = this.resize;
		this.frame.onmouseup = this.endResize;
		this.pic.onmouseup = this.endMove;
		this.pan.onmouseup = this.endResize;
		this.pic.onclick = this.tagging;
	},
	getElement: function(id,parentEl) {
		var el = getEl(id);
		if(!el) {
			el = document.createElement("div");
			el.id = id;
			el.className = id + "_css";
			parentEl.appendChild(el);
		}
	  return el;
	},
	getPhotoDimension: function(el) {
	 	this.picw = el.width;
		this.pich = el.height;
	},
  setElDimension: function(el,w,h) {
		if(!el) {
			dpd("there is no element to being set dimension");
			return false;
		}
		if(w > 0) {
			el.style.width = w + "px"; } 
		if(h > 0) {
			el.style.height = h + "px";
	 	}
	},
	setElPos: function(el,left,top) {
		if(!el) {
			dpd("there is no element to being set position");
			return false;
		}
		el.style.left = left + "px";
	  el.style.top = top + "px";
	},
  display: function(el) {
	  el.style.display = "block";
	},
	hide: function(el) {
		el.style.display = "none";
	},
/*
	function to show a frame in the photo
	-----------
	PARAMETERS:
	frameId: the id of the frame to being show
	left: the distance from frame left age to the photo left age
	top:  the distance from frame top age to the photo top age
	width: the frame width
	height: the frame height
	pars:  the additional parameters
	------------
	RETURN VALUE: 
	true | false 
*/	
  showFrame: function(frameEl,left,top,width,height,pars) {
		//photoTag.frame = photoTag.getElement(frameId);
		photoTag.setElPos(photoTag.frame,left,top);
		photoTag.setElDimension(photoTag.frame,width,height);
		photoTag.setElDimension(this.inner,(width-4),(height-4));
		photoTag.display(photoTag.frame);
		//this.status = "frame_is_shown";
	},
	showFrameList: function(frameList) {
		for(var i=0; l<frameList.legth; i++) {
			frameList[i].el= this.getElement(frameList[i].id,frameList[i].divId);
			photoTag.setElDimension(frameList[i].el,frameList[i].width,frameList[i].height);
			frameList[i].inner = this.getElement(("inner" + i),frameList[i].el);
		}
	},
/*
	function to hide the frame in the photo
	---
	PARAMETERS:
	frameId: the id of the frame to being hide
	---
	RETURN VALUES:
	
*/
  hideFrame: function() {
		photoTag.hide(photoTag.frame);	
	 	//this.status = "frame_is_hidden";
	},
/*
	function to show the tag pan beside a frame
	---
	PARAMS:
	panId:   the id for this pan
	frameId: the id of the frame to which this tag pan show with;
	left,top: position of the tag pan relative to frame, if frameId == -1, this position absolute.
	width,height: whidth & height of the tag pan.
	---
	RETURN:
	true|false
	*/
	showTagPan: function(panId,frameId,left,top,width,height,pars) {
	  //photoTag.pan = photoTag.getElement(photoTag.panId); 	
	  //photoTag.setElDimension(photoTag.pan,width,height); 
	  photoTag.setElPos(photoTag.pan,left,top);
		photoTag.display(photoTag.pan);
		status="pan_is_shown";
	},
/*
	function to hide the tag pan
	---
	PARAMS:
	panId: the id for the pan
*/
	hidePan: function() {
		photoTag.hide(photoTag.pan);
		if(this.status=="not_ready_to_action") return true;
		if($("targetId")) $("targetId").value = "";
		this.status = "normal_state";
		newlist(event);
		//this.status = "pan_is_hidden";
	},
/*
*/
	move: function(e) {
		if((photoTag.status != 'begin_to_move') || (photoTag.status == "moving")) return true;
		photoTag.albumMousePos(e,"edge");
		photoTag.mouseOffX = mousex - photoTag.mousex;
		photoTag.mouseOffY = mousey - photoTag.mousey;
		photoTag.leftToPic += photoTag.mouseOffX;
		photoTag.topToPic += photoTag.mouseOffY;
		photoTag.frame.style.left = photoTag.leftToPic + "px";
	 	photoTag.frame.style.top = photoTag.topToPic + "px";
		photoTag.setElPos(photoTag.pan,(photoTag.leftToPic+photoTag.frameWidth+23), photoTag.topToPic);
		photoTag.mousex = mousex;
		photoTag.mousey = mousey;
	},
	tagging:function(e) {
		//debugOut(photoTag.status);
	  if(photoTag.status == 'not_ready_to_action')  {
			document.location.href= photoTag.pic.alt; 
			return true; 
		}
		else { 
			photoTag.setTag(e); return true;
		}
	},
	beginAction:function(e) {
		
		if((photoTag.status != "ready_to_move")&&(photoTag.status!= "ready_to_resize")) return true;
	  if(photoTag.status == "ready_to_move") photoTag.beginMove(e);
		else photoTag.beginResize(e);
	},
	resize: function(e) {
		if(photoTag.status == "not_ready_to_action") {
			photoTag.pic.style.cursor = "pointer";
			return true;
		}
		photoTag.albumMousePos(e,"edge");
		if( !photoTag.testArea(mousex,mousey,photoTag.frame,(photoTag.frameWidth+23),(photoTag.frameHeight+5))) {
			if((photoTag.status != "resizing")&&(photoTag.status != "begin_to_resize")) {
				photoTag.status = "normal_state"; 
				photoTag.pic.style.cursor = "crosshair";
		  }
		} else {
			//mouse position is in the inner area
			if((photoTag.status != "ready_to_resize") && (photoTag.status != "resizing")) {
				photoTag.pic.style.cursor = "move";
			}
		}
		if((photoTag.status == "begin_to_resize") || (photoTag.status == "resizing")) {
			if(photoTag.status == 'begin_to_resize') {
				var targ;
				if (!e) var e = window.event;
				if (e.target) targ = e.target;
				else if (e.srcElement) targ = e.srcElement;
				if (targ.nodeType == 3) // defeat Safari bug
					targ = targ.parentNode.id;
				photoTag.direction = targ.id;
				photoTag.status = "resizing";
			}
			photoTag.mouseOffX = mousex - photoTag.mousex;
			photoTag.mouseOffY = mousey - photoTag.mousey;
			var newWidth = photoTag.frameWidth + photoTag.mouseOffX;
			var newHeight = photoTag.frameHeight + photoTag.mouseOffY;
			/*if(newWidth < FRAME_MIN_W) {
				newWidth = FRAME_MIN_W;
				photoTag.mouseOffX = newWidth - photoTag.frameWidth;
			}
			if(newHeight < FRAME_MIN_H) {
				newHeight = FRAME_MIN_H;
				photoTag.mouseOffY = newHeight - photoTag.frameHeight;
			}*/
			switch(photoTag.direction) {
				case "leftTop": 
					photoTag.leftToPic += photoTag.mouseOffX;
					photoTag.topToPic += photoTag.mouseOffY;
					photoTag.frameWidth -= photoTag.mouseOffX;
					photoTag.frameHeight -= photoTag.mouseOffY;
					break;
				case "rightTop":
					photoTag.topToPic += photoTag.mouseOffY;
					photoTag.frameWidth += photoTag.mouseOffX;
					photoTag.frameHeight -= photoTag.mouseOffY;
					break;
				case "leftBottom":
					photoTag.leftToPic += photoTag.mouseOffX;
					photoTag.frameWidth -= photoTag.mouseOffX;
					photoTag.frameHeight += photoTag.mouseOffY;
					break;
				case "rightBottom":
					photoTag.frameWidth += photoTag.mouseOffX;
					photoTag.frameHeight += photoTag.mouseOffY;
					break;
			}
			photoTag.setElPos(photoTag.frame,photoTag.leftToPic,photoTag.topToPic);
			photoTag.setElDimension(photoTag.frame, photoTag.frameWidth, photoTag.frameHeight);
			photoTag.setElDimension(photoTag.inner, (photoTag.frameWidth-4), (photoTag.frameHeight-4));
			photoTag.setElPos(photoTag.pan,(photoTag.leftToPic+photoTag.frameWidth+23), photoTag.topToPic);
			photoTag.mousex = mousex;
			photoTag.mousey = mousey;
	 	}
		else {
			photoTag.move(e);
		}
	},
	refresh:function(e) {
		if((photoTag.pan.style.display == "none")) return true;
		photoTag.showFrame(photoTag.frame,photoTag.leftToPic,photoTag.topToPic,photoTag.frameWidth,photoTag.frameHeight,"");
	  photoTag.frame.style.border=DASHED_OUTER;
		photoTag.inner.style.border=DASHED_INNER;
		$("leftTop").style.display = ""; 
		$("rightTop").style.display = ""; 
		$("leftBottom").style.display = ""; 
		$("rightBottom").style.display = ""; 
	},
	setTag: function(e) {
		if(!photoTag.pageloaded) { alert("抱歉，要点的图还没有完全下载完，请稍后再试"); return false; }
		if(photoTag.status == 'ready_to_move') return true;
		var cursorx,cursory,left,top;
		if(!photoTag.picId) {
		  alert("the pic object is not defined");
			return true; 
		}
		var pic = photoTag.pic;
		photoTag.frame.style.border=DASHED_OUTER;
		photoTag.inner.style.border=DASHED_INNER;
		$("leftTop").style.display = ""; 
		$("rightTop").style.display = ""; 
		$("leftBottom").style.display = ""; 
		$("rightBottom").style.display = ""; 
		var w = pic.width, h = pic.height;
		//var maxX = w-photoTag.frameWidth, maxY = h-photoTag.frameHeight;
		photoTag.picx = findPosX(pic);
		photoTag.picy = findPosY(pic);
		var maxX = w + photoTag.picx, maxY = h+photoTag.picy;
		
		//var maxX = w, maxY = h;
		if(1) {
			photoTag.albumMousePos(e);	
			left = mousex - photoTag.frameWidth/2;
			top = mousey - photoTag.frameHeight/2;
			//框到图片边缘的位置
			photoTag.leftToPic = left;
			photoTag.topToPic = top;
 			if(photoTag.leftToPic < 0) {
				left -= photoTag.leftToPic;
				photoTag.leftToPic = 0;
			}
			if(photoTag.topToPic < 0) {
				top -= photoTag.topToPic;
				photoTag.topToPic = 0;
			}
			if(photoTag.leftToPic>maxX) {
			  left -= (photoTag.leftToPic - maxX) 
				photoTag.leftToPic = maxX;
			}
 			if(photoTag.topToPic>maxY) {
			  top -= (photoTag.topToPic - maxY) 
				photoTag.topToPic = maxY;
			}
			photoTag.showFrame(photoTag.frameId,left,top,photoTag.frameWidth,photoTag.frameHeight,"");
			photoTag.setElDimension(photoTag.inner,(photoTag.frameWidth-4),(photoTag.frameHeight -4));
			
		  photoTag.showTagPan(photoTag.panId,photoTag.frameId,(left + photoTag.frameWidth + 23),top,photoTag.panWidth,photoTag.panHeight);
			
			if($("targetId")) $("targetId").focus();
		  photoTag.pic.style.cursor="move"; 
			photoTag.status="ready_to_move";
		}
	},
	addToTagList: function(photoId, ownerId, ownerName, target) {
		var targetStr = target;
		addTag(photoId,(this.leftToPic-this.picx),(this.topToPic-this.picy),this.frameWidth,this.frameHeight,this.picw,this.pich,targetStr,ownerId,ownerName);
	},
	hideTag: function() {
		this.hideFrame();
	 	//this.hideTagger();
	},
	showTag: function(left,top,width,height,taggerId,taggerName) {
		//if(this.status != "not_ready_to_action") return false;
		this.picx=findPosX(this.pic);
		this.picy=findPosY(this.pic);
		photoTag.frame.style.border=SOLID_OUTER;
		this.inner.style.border=SOLID_INNER;
		$("leftTop").style.display = "none"; 
		$("rightTop").style.display = "none"; 
		$("leftBottom").style.display = "none"; 
		$("rightBottom").style.display = "none"; 

		photoTag.showFrame(photoTag.frameId,(left+this.picx),(top+this.picy),width,height,"");	
		//photoTag.showTagger((left+this.picx),(top+this.picy),width,height,taggerId,taggerName);
		status="tag_is_shown";
	},
 	showTagger:function(left,top,width,height,id,name) {
		if(tagger == 0 ) createTagger();
		tagger.innerHTML='由<a href="http://renren.com/profile.do?id="' + id + '>' + name + '</a>圈';
		tagger.style.left = left + "px";
		tagger.style.top = top+height+5 + "px";
		tagger.style.display="block";
		return false;
	},
	hideTagger: function() {
		tagger.style.display="none";
	},
/*
	function to write info into tag pan
	---
	PARAMS:
	plugins: arrays store the functions which should be exec to fill the info into the tag pan
	*/
	drawPan: function(text) {
	  photoTag.pan.innerHTML = text; 
	},
	hasPlugin : function(n) {
		return typeof(this.plugins[n]) != "undefined" && this.plugins[n] != null;
	},
	addPlugin : function(n, p) {
		p.baseURL = this.baseURL + "/plugins/" + n;
		this.plugins[n] = p;
	}, 
	loadScript : function(url) {
		for (var i=0; i<this.loadedFiles.length; i++) {
			if (this.loadedFiles[i] == url)
			return;
		}
		document.write('<sc'+'ript language="javascript" type="text/javascript" src="' + url + '"></script>');
		this.loadedFiles[this.loadedFiles.length] = url;
	},
	inMoveArea: function(e) {
		if(photoTag.status !="normal_state") return;
		photoTag.inner.style.cursor = "move";
		photoTag.pic.style.cursor = "move";
		photoTag.status = "ready_to_move";
	},
	outMoveArea:function(e) {
		if(photoTag.status == "ready_to_move") {
			photoTag.status = "normal_state";
		}
	},
	inResizeArea: function(e) {
	  //debugOut("readyToResize");
		if((photoTag.status != "normal_state") && (photoTag.status != "ready_to_move")) return;
		var targ;
		if (!e) var e = window.event;
		if (e.target) targ = e.target;
		else if (e.srcElement) targ = e.srcElement;
		if (targ.nodeType == 3) // defeat Safari bug
			targ = targ.parentNode;
		switch(targ.id) {
			case "leftTop":
				$("leftTop").style.cursor = "nw-resize";	
				break;
			case "rightTop":
				$("rightTop").style.cursor = "ne-resize";	
				break;
		  case "leftBottom":
				$("leftBottom").style.cursor = "sw-resize";	
				break;
			case "rightBottom":
				$("rightBottom").style.cursor = "se-resize";	
				break;
		}
		photoTag.status = "ready_to_resize";
	},
	outResizeArea: function(e) {
		if(photoTag.status == "ready_to_resize") {
			photoTag.status = "ready_to_move"; 
		} 
	},
	testArea: function(x,y,el,width,height) {
		var elx = findPosX(el), ely = findPosY(el), deltax = x - elx; deltay = y - ely;
	  if((deltax > 0 ) && (deltay >0 ) && (deltax < width) && (deltay < height)) {
			return true;
		} else {
			return false;
	 	}
	},
	beginResize: function(e) {
		//if((photoTag.status != "ready_to_move") && (photoTag.status != "ready_to_resize")) return;
		 
		//debugOut(photoTag.status);
		if(photoTag.status != "ready_to_resize") return;
		photoTag.status = "begin_to_resize";
		//photoTag.frame.style.cursor = "move";
		photoTag.mousex = mousePosX(e);
		photoTag.mousey = mousePosY(e);
	},
	endResize: function(e) {
		if((photoTag.status == "resizing") || (photoTag.status == "begin_to_resize")) {
			var targ;
			if (!e) var e = window.event;
			if (e.target) targ = e.target;
			else if (e.srcElement) targ = e.srcElement;
			if (targ.nodeType == 3) // defeat Safari bug
				targ = targ.parentNode;
			//targ.style.cursor = "auto";	
			photoTag.status="ready_to_resize";
		}
	},
	beginMove: function(e) {
		if((photoTag.status != "ready_to_move")) return true;
		photoTag.status = "begin_to_move";
		photoTag.inner.style.cursor = "move";
		photoTag.mousex = mousePosX(e);
		photoTag.mousey = mousePosY(e);
		if (!e) var e = window.event;
		e.cancelBubble = true;
	 	if (e.stopPropagation) e.stopPropagation();
	},
  endMove: function(e) {
		//if(photoTag.status != "normal_state") alert(photoTag.status);
		if((photoTag.status == "moving") || (photoTag.status == "begin_to_move")) {
			var targ;
			if (!e) var e = window.event;
			if (e.target) targ = e.target;
			else if (e.srcElement) targ = e.srcElement;
			if (targ.nodeType == 3) // defeat Safari bug
				targ = targ.parentNode;
			//targ.style.cursor = "move";	
			photoTag.status="ready_to_move";
		}
	}
}
var photoTag = new PhotoTag();
var myDate = new Date();
var return_result;
var left, top,height,width, targetStr,albumTags = '<div id="albumTags"></div>';
var Qtype, Qhostid, Qhostname, Qphotoid, Qownerid, Qownername, Qfriends=0, Qtag=0, Qclassid, Qimgtitle;
function addTag(photoId,leftToPhoto,topToPhoto,frameWidth,frameHeight,photoWidth,photoHeight,target, ownerId, ownerName) {
	if(photoId=="") {
		alert("圈人出错啦，请刷新页面后重试");
		return false;
	}
	if(target == "") {
		alert("抱歉，名称不能为空");
		photoTag.frame.style.display="block";
		photoTag.pan.style.display="block";
		$("targetId").focus();
		return true;
	}
	var url = 'tagphoto.do';
	if(Qtype == 2) {
		url = 'schooltagphoto.do';
	}
	var dt = new Date();
	var pars =  'photoId='+ photoId + 
							'&owner='+ ownerId + 
							'&leftToPhoto=' + leftToPhoto + 
							'&topToPhoto=' + topToPhoto +
							'&frameWidth=' + frameWidth +
							'&frameHeight=' + frameHeight +
							'&photoWidth=' + photoWidth +
							'&photoHeight=' + photoHeight +
							'&target=' + target +
							'&t=' + dt.getTime();
	if(Qtype == 2) {
		pars += '&classid=' + Qclassid;
	}
	//debugOut(pars);
	var myAjax = new Ajax.Request(
				url, 
				{
							method: 'post', 
							parameters: pars, 
							onComplete: showResponse,
							onFailure: showError
				});
 	left = leftToPhoto;
	top  = topToPhoto;
	width = frameWidth;
	height = frameHeight;
  targetStr = target;
	//alert("targetStr: " + targetStr);
}
function showResponse(r) {
	return_result = r.responseText;
	var count = 0;
	var pos = 0;
	postResult[0] = "";
	postResult[1] = "";
	postResult[3] = "";
	//alert(return_result);
	pos = return_result.indexOf(",");
	while( (pos != -1) && count<2) {
		postResult[count++] = return_result.substring(0,pos); 
		return_result = return_result.substring(pos+1);
 		pos = return_result.indexOf(",");
	}
	postResult[2] = return_result;
	 
	switch(postResult[0]) {
		case "1":
			htmlStr = '抱歉，输入的名称不能为空，';
			break;
		case "2":
			htmlStr = '抱歉，输入的名称过长，';
			break;
		case "4":
		case "6":
			htmlStr = '<div class="title">圈人成功</div>';
			break;
	 	case "8": 
		case "10":
			//htmlStr = '<div class="title">你的标柱已经发送给' + photoOwner + "和" + postResult[2] + '进行验证' + '</div>';
			htmlStr = '<div class="title">圈人成功，申请已经发送，</div>';
	 		break;
	}
	htmlStr += "你可以继续圈人，或者点右边的“完成”按钮";
	 
	$('tagNote').innerHTML = htmlStr;				
	$('photoNote').style.display = "block";
	if(postResult[0]<4) {
		return true;
	}
	var str ="";
	if($('tagList').innerHTML.indexOf(": ") == -1) {
			if(!getEl("phototitle")) {
				str += "照片中有";	
			}
			str += ": ";
	} else {
		str+='<span class="pipe">&bull;</span>';	
	}
	var eventHtml = 'onmouseover="photoTag.showTag(' + left + ',' + top + ',' + width + ',' + height +'); return false;" onmouseout="photoTag.hideTag()">'; 
	if((postResult[0] == 4) || (postResult[0] == 8)) {
		str += '<span ' + eventHtml + postResult[2] + '</span>(';
	}
	if((postResult[0] == 6) || (postResult[0] == 10)) {
		str += '<a href="http://renren.com/profile.do?id=';
		str += targetStr + '"';
		str += eventHtml;
		str += postResult[2] + '</a>(';
		if(Qtype == 1) {
			str += '<a href="http://photo.renren.com/someonetagphoto.do?id=' + targetStr + '"' + eventHtml + '照片</a>';
			str += '<span class="pipe">|</span>';
		}
	}
	if(postResult[0] >=4) {
		if(Qtype == 1) {
			str += '<a href="http://photo.renren.com/delphototag.do?id=' + postResult[1] + '"' + eventHtml + '删除</a>)';
		} else if(Qtype == 2) {
			str += '<a href="http://class.renren.com/schooldelphototag.do?classid=' + Qclassid + '&id=' + postResult[1] + '"' + eventHtml + '删除</a>)';
		}
	}
	$("tagList").innerHTML += str;
 	return value;
 	/*
	0: ${requestScope.result},1: ${requestScope.tagId},2: ${requestScope.targetName}
  
	resutl:
	0表示form提交出错
	1表示target对象为空
	2表示target超出12个字符
	4表示在自己的照片上标识成功，target不是具体用户
	6表示在自己的照片上标识成功，target是站内用户
	8表示在别人的照片上标识成功。
	10表是在别人的照片上标识成功，会显示  
	*/
}
function showError(t) {
	var errmsg = t.status + ' -- ' + t.statusText; 
	alert("抱歉，出错了；错误信息: " + errmsg + " 麻烦点页面底部的 “给管理员留言”报告错误");
}
function insertToPan(albumId) {
	var url = 'http://photo.renren.com/getalbumtaglist.do';
	var pars =  'id='+ albumId + 
							'&t=' + myDate.getTime();
	var myAjax = new Ajax.Request(
				url, 
				{
							method: 'post', 
							parameters: pars, 
							onComplete: getAlbumTagList,
							onFailure: showError
				});
}
function getAlbumTagList(r) {
	var data = eval('(' + r.responseText + ')');
	if(data.names.length == 0) return false;
	var tmp = '';
	var tmpId = 0; 
 	tmp = '<ul>';
	for(var i=0; i<data.names.length; i++) {
		tmpId = data.names[i].id;
		if( tmpId == 0) {
			tmpId = "'" + data.names[i].name + "'"; 
		}
		tmp += '<li><input type="checkbox" onclick="return submitAction(' + tmpId + ');" />' + data.names[i].name + '</li>';
	}
	tmp += '</ul>';
	$("albumTags").innerHTML = tmp;
}
function submitAction(targetId) {
	photoTag.hideFrame(); 
	photoTag.hidePan(); 
	photoTag.addToTagList(Qphotoid, Qownerid, Qownername, targetId);
	return false;
}
function cancelAction() {
	photoTag.hideFrame(); 
	photoTag.hidePan();
}	
function whatIsId() {
	var x = photoTag.picx - 200;
	var y = photoTag.picy;
	var openstr = 'left='+ x +',top=' + y + ',width=660,height=450,status=no,toolbar=no,menubar=no,scrollbars=no,resizable=yes';
	//alert("openstr" + openstr);
	var win=window.open((url + '/info/id.jsp') ,'',openstr);
	win.focus();
	return false;
}
function myDrawPan(string) {
	var str = "<div id='target'>" +
						"<form action='#' onsubmit='return submitAction($F(\"targetId\"))'>";
						str += "<div class='target-title'>";
						str += "<h3>输入名字或标签: </h3>";
						str += "<div><input id='targetId' type='text' onkeyup='newlist(event)' /></div>";
						str += "<div id='fintro'><h3>或选择一个好友: </h3></div>";
						str += "</div>";
						str += "<div id='target-body' class='target-body'><ul id='flist' style='height: 200px; overflow: auto'>";
						//str += "<li class='myself'><input type='checkbox' onclick='return submitAction(Qhostid)' />" + Qhostname + "(我)</li>";
                        //列出所有返回的好友列表
					    var i = 0;
						while(Qtag[i]){
						     str +="<li><input type='checkbox' id='f" + Qtag[i].id +"' name='f" + Qtag[i].id +"' onclick='return submitAction(" + Qtag[i].id +");' /><label for='f" + Qtag[i].id +"'>" + Qtag[i].name + "</label></li>"; 
					         i++;
						}
						str +='<li><hr></li>';
						i = 0;
					    while(Qfriends[i]){
						     str +="<li><input type='checkbox' id='f" + Qfriends[i].id +"' name='f" + Qfriends[i].id +"' onclick='return submitAction(" + Qfriends[i].id +");' /><label for='f" + Qfriends[i].id +"'>" + Qfriends[i].name + "</label></li>"; 
					         i++;
						}
						str += "</ul></div>";
						str += "<p class='target-action'>" +
						"<input type='submit' value='确定' class='inputsubmit' /> " +
						"<input type='button' value='取消' class='inputsubmit gray' onclick='cancelAction()' />" +
						"</p>" +
						"</form>" +
						"</div>";
	return str;
}

function newlist(e){
   if(e.keyCode==27){
	   cancelAction();
   }
   var str = "";
   //生成新的列表
   keyword =  $F("targetId");
   var i = 0;
   var j = 0; // line
   var k = 0; //display or not
   while(Qtag[i]){
						    if(keyword==""){
								str +="<li><input type='checkbox' id='f" + Qtag[i].id +"' name='f" + Qtag[i].id +"' onclick='return submitAction(" + Qtag[i].id +");' /><label for='f" + Qtag[i].id +"'>" + Qtag[i].name + "</label></li>";
							    j++;
								k++;
							}else{
							     if((Qtag[i].name).indexOf(keyword,0)==-1){
	                             }else{
							      str +="<li><input type='checkbox' id='f" + Qtag[i].id +"' name='f" + Qtag[i].id +"' onclick='return submitAction(" + Qtag[i].id +");' /><label for='f" + Qtag[i].id +"'>" + Qtag[i].name + "</label></li>";
						          j++;
								  k++;
								 }   
							}
                           i++;
   }
   i = 0;
   if(j){
     str +='<li><hr></li>';
   } 
   while(Qfriends[i]){
						    if(keyword==""){
								str +="<li><input type='checkbox' id='f" + Qfriends[i].id +"' name='f" + Qfriends[i].id +"' onclick='return submitAction(" + Qfriends[i].id +");' /><label for='f" + Qfriends[i].id +"'>" + Qfriends[i].name + "</label></li>";
							}else{
							     if((Qfriends[i].name).indexOf(keyword,0)==-1){
	                             }else{
							      str +="<li><input type='checkbox' id='f" + Qfriends[i].id +"' name='f" + Qfriends[i].id +"' onclick='return submitAction(" + Qfriends[i].id +");' /><label for='f" + Qfriends[i].id +"'>" + Qfriends[i].name + "</label></li>";
						          k++;
								 }   
							}
                           i++;
   }
   
   if(k==0){
      document.getElementById("target-body").style.display="none";
	  document.getElementById("fintro").style.display="none";
   }else{
      document.getElementById("target-body").style.display="";
	  document.getElementById("fintro").style.display="";
      document.getElementById("flist").innerHTML=str;
   
   }

}

function onPhotoReplyClick(name,id, forceWhisper) {
	//getEl("cmtbody").focus();
	//getEl("cmtbody").value='回复'+name+': ';
	$("cmttoid").value=id;
	document.location.href="#comment";
	var tmp =  '回复'+name+': ';
	$('cmtbody').value = tmp;
	//SetHTML(tmp,"simplerte");	
	//SetFocus("simplerte");
	
	if (forceWhisper) {
		try {
		$('realWhisper').value = 'true';
		$('whisper').checked = true;
		$('whisper').disabled = true;
		} catch (e) {}
	} else {
		try {
		$('realWhisper').value = 'false';
		$('whisper').checked = false;
		$('whisper').disabled = false;
		} catch (e) {}
	}
}

function onSend(wordid) {
	var str=getEl(wordid).innerHTML;
	if(str.substring(8,11)!="回复") {
		var origmsg="<p class='reply'>";
		origmsg+=str;
		origmsg+="</p>";
		var out = getEl('message').value+origmsg;
		getEl('message').value=out;
	}
}
function cc(event) {
	try
	{
		var ev=event.srcElement;
		var r=ev.createTextRange();
	}
	catch (e)
	{
		return ;
	}
	r.moveStart('character',ev.value.length);
	r.collapse(true);
	r.select();
}

function initTag(type, hostid, hostname, photoid, ownerid, ownername, classid)
{
	Qtype = type;
	Qhostid = hostid;
	Qhostname = hostname;
	Qphotoid = photoid;
	Qownerid = ownerid;
	Qownername = ownername;
	Qclassid = classid;
	photoTag.init({picDivId:"photo",status:"not_ready_to_action",drawPan_cb:"myDrawPan"});
	photoTag.initPageElement();
}

function beginTag()
{
	if(Qtype == 1) {
		if(!Qfriends) {
			var dt = new Date();
			var myAjax = new Ajax.Request("gettagfriends.do", {method:'post', parameters:'owner=' + Qownerid +'&t=' + dt.getTime() + '&id=' + Qphotoid, onComplete:getFriendsComplete, onFailure:getFriendsFailure});
		} else {
			readyTag();
		}
	} else {
		readyTag();
	}
}

function getFriendsComplete(r)
{
	var Qlist = eval('('+r.responseText+')'); 
	Qfriends = Qlist.friends_ajax;
	Qtag = Qlist.tag_friends_ajax;
	readyTag();
}

function getFriendsFailure(r)
{
	alert("系统错误，请稍候再试。");
}

function readyTag()
{
	photoTag.initPageElement();
	photoTag.status = 'normal_state';
	photoTag.setCursor(photoTag.pic, 'crosshair');
	$('photoNote').style.display = 'block';
	Qimgtitle = photoTag.pic.title;
	photoTag.pic.title = '点击选择要圈的区域';
}

function endTag()
{
	photoTag.status = 'not_ready_to_action';
	photoTag.setCursor(photoTag.pic, 'auto');
	photoTag.hideFrame();
	photoTag.hidePan();
	$('photoNote').style.display = 'none';
	photoTag.pic.title = Qimgtitle;
}

var tagger = 0; 
function createTagger() { 
	tagger = document.createElement("div");
	tagger.id = "tagger";
	tagger.className = "tagger_css";
	document.body.appendChild(tagger);
 	
}

//postComment.do form checker
function fnCommentPhotoCK() {
	//fnGetSimpleEditorContent("simplerte","cmtbody");
	var numstr = getEl("cmtbody").value.length;
	if(numstr == 0)
	{
		alert("评论内容不能为空");
		return false;
	}
	return true;  

}


function commentPhoto(frm)
{
	var cmt = Trim(getEl("cmtbody").value);
	if(cmt.length == 0) {
		alert("请填写评论");
		return;
	}
	if(cmt.length > 2000) {
		alert("评论不能多于2000字符");
		return;
	}
	cpBtn(true, "请稍候", "subbutton gray");
	cpMsg("", "none");
	new XN.NET.xmlhttp("/ajaxcommentphoto.do",
			XN.FORM.serialize(frm),
			function(r) {
				if(r.responseText.substring(0, 3) == "af:") {
					cpMsg(r.responseText.substring(3), "block");
				} else {
					$("talk").innerHTML += r.responseText;
					// 再回复不再抄送到第三人
					$("cmttoid").value = '0';
					getEl("cmtbody").value = '';
					try {
					$('realWhisper').value = 'false';
					$('whisper').checked = false;
					$('whisper').disabled = false;
					} catch (e) {}
				}
				cpBtn(false, "发表评论", "subbutton");
			},
			{
				onError:function() {
					cpMsg("系统忙，请稍候再试。", "block");
					cpBtn(false, "发表评论", "subbutton");
				}
			}
	);
}

function cpMsg(h, d)
{
	var _e = $("ajax_msgerror");
	if(_e) {
		_e.innerHTML = h;
		_e.style.display = d;
	}
}

function cpBtn(d, v, c)
{
	var _e = $("editorFormBtn");
	if (_e) {
		_e.disabled = d;
		_e.value = v;
		_e.className = c;
	}
}

function deletePhotoComment(id, owner)
{
	cpMsg("", "none");
	new XN.NET.xmlhttp("/ajaxdeletephotocomment.do",
			"id=" + id + "&owner=" + owner,
			function(r) {
				if(r.responseText.substring(0, 3) == "af:") {
					cpMsg(r.responseText.substring(3), "block");
				} else if(r.responseText.substring(0, 3) == "ao:") {
					$("talk" + id).style.display = 'none'
				}
			},
			{
				onError:function() {
					cpMsg("系统忙，请稍候再试。", "block");
      	}
      }
	);
}


//=============================================================================
// 以下代码由快速编辑照片描述使用 lei.chen@opi-corp.com
// 部分依赖照片留言的代码
//=============================================================================
var photoTitleEditDiv = 'photoTitleEditor';
var photoTitleEditErrDiv = 'photoTitleEditErr';
var photoTitleEditTitleDiv = 'photoTitleTitle';
var photoTitleEditTextArea = 'description';

function photoTitleEditShowError(code, err) {
	var e = $(photoTitleEditErrDiv);
	if (e) {
		e.innerHTML = err;
		e.style.display = '';
	} else {
		alert('错误: 没有找到 '+photoTitleEditErrDiv);
	}
}

function photoTitleEditHideError() {
	var e = $(photoTitleEditErrDiv);
	if (e) {
		e.hide();
	} else {
		alert('错误: 没有找到 '+photoTitleEditErrDiv);
	}
}

function photoTitleEditToggle(forceClose) {
	var e = $(photoTitleEditDiv);
	var t = $(photoTitleEditTitleDiv);
	if (e) {
		if (forceClose) {
			e.hide();
			t.show();
			return;
		}
		if (e.style.display == 'none') {
			e.show();
			t.hide();
			var e2 = $(photoTitleEditTextArea);
			if (e2) e2.focus();
		}else{
			e.hide();
			t.show();
		}
	} else {
		alert('错误，没有找到 '+photoTitleEditDiv);
	}
}

function photoTitleEditSubmit(id, title) {
	var url = "/ajaxeditphoto.do";
	var params = "id="+id+"&description="+encodeURIComponent(title);
	new Ajax.Request(url, {
		method: 'post',
		postBody: params,
		onSuccess : function(trans) {
			var json = eval('('+trans.responseText+')');
			if (json && json.code == 0) {
				var e = $(photoTitleEditTitleDiv);
				if (e) {
					if (json.msg == '') {
						e.innerHTML = '单击此处添加照片描述';
					} else {
						e.innerHTML = json.msg.replace("\n", "<br/>");
					}
					photoTitleEditToggle(true);
					photoTitleEditHideError(); // hide previous error
				} else {
					alert('错误，没有找到 '+photoTitleEditTitleDiv);
				}
			} else if (json) {
				photoTitleEditShowError(json.code, json.msg);
			} else {
				// 不该出现这样的错误
				photoTitleEditShowError(photoCommentErrorAjaxResponse);
			}
		},
		onFailure: function(trans) {
			photoTitleEditShowError(photoCommentErrorAjaxResponse);
		}
	});
}

