﻿/// <reference path="jquery-1.3.2-vsdoc2.js" />
//应用扩展
Cute.common = {
	confirm: function(msg, url) {
		if (arguments.length == 1) {
			url = msg;
			msg = '真的要删除吗？';
		}
		Cute.dialog.confirm(msg, {
			yes: function() {
				if (url.constructor == String) {
					location.href = url;
				} else if (url.constructor == Function) {
					url();
				}
			}
		});
		return false;
	},
	photo:{
		get: function(options, callback){
			callback = callback || $.noop;
			Cute.api.get("moretopics",$.extend({
				pagesize: 8,
				tags: "",
				gender:""
			}, options || {}),callback);
		},
		list:function(options, callback){
			callback = callback || $.noop;
			var opt = $.extend({
				el:document.body,
				pagesize: 8,
				tags:"",
				page:1,
				listtype:"recommend",
				gender:""
			}, options || {});
			var loading;
			var loading = $('<li class="photo_loading">下页图片加载中…</li>').appendTo(opt.el);
			this.get({
				pagesize: opt.pagesize,
				listtype: opt.listtype,
				tags: opt.tags,
				page: opt.page,
				gender: opt.gender
			},function(json){
				loading.remove();
				if(json.code == 1 && json.result.length > 0){
					this.page = opt.page + 1;
					$(opt.el).append(Cute.template("PHOTO_LIST",json));
					callback();
				}
			}.bind(this));
		},
		clip: function(){
			var imgw,imgh;
			this.preview = function(img, selection) { 
				if(selection){
					if(selection.x2 - selection.x1 > 0){
						$("#x").val(selection.x1);
						$("#y").val(selection.y1);
						$("#width").val(selection.x2 - selection.x1);
						$("#height").val(selection.y2 - selection.y1);
					}else{
						$("#x,#y,#width,#height").val(0);
					}
				}
			}
			imgw = $('#bigimg').width();
			imgh = $('#bigimg').height();
			$('#bigimg').imgAreaSelect({
				onSelectChange : this.preview
			});
		}
	},
	write: function(id, fn) {
		if (!id) return;
		if (!$(document).data("write" + id)) {
			Cute.api.get("write", { id: id }, function(json) {
				if (json.code == 1) {
					$(document).data("write" + id, json.result);
					fn(json.result);
				}
			});
		} else {
			fn($(document).data("write" + id));
		}
	},
	answer: function(topicid,markid){
		if(!Cute.common.user.checklogin())return;
		Cute.dialog.layer(null,{
			content:"#answerDialog",
			mask:true,
			blur:true,
			open:{
				callback:function(){
					$("h3.title",this.pannel).html($("#thingTitle" + markid).html()).contents().not("kbd,span.icon").remove();
					var obj = $("input[name=content]",this.pannel).focus();
					$("span.submit",this.pannel).unbind("click").bind("click",function(){
						var v = obj.val().trim();
						if(v == ""){
							alert("网址不能为空，请确认");
							obj.focus();
							return false;
						}
						if(!new RegExp("^http[s]?:\\/\\/([\\w-]+\\.)+[\\w-]+([!#\\w-./?%&=:\\+]*)?$").test(v)){
							alert("填写的网址格式不正确，请确认");
							obj.focus();
							return false;
						}
						$("button",this).attr("disabled", true).css("color","#888");
						Cute.api.get("answer",{
							topicid:topicid, 
							markid:markid,
							content:obj.val().trim()
						},function(json){
							this.close();
							$("button",this).attr("disabled", false).css("color","");
							if(json.code == 1){
								location.reload();
							}else{
								Cute.dialog.notice(json.result, { className:"dialog_error"});
							}
						}.bind(this));
						return false;
					}.bind(this));
					$("span.cancel",this.pannel).unbind("click").bind("click",this.close.bind(this));
				}
			}
		});
	},
	url:{
		preview: function(url){
			var num_iid = '';
			var list = {};
			$.each(url.match(/(?:[\?|\&])[^\=]+=[^\&|#|$]*/gi) || [], function(n, item) {
				var _item = item.substring(1);
				var _key = _item.split("=", 1)[0];
				var _value = _item.replace(eval("/" + _key + "=/i"), "");
				list[_key.toLowerCase()] = _value;
			});
			num_iid = list["id"] || list["item_num_id"];
			if(num_iid){
				Cute.dialog.ajax("商品预览",{
					action:"write",
					params:{
						name:2,
						num_iid:num_iid
					},
					result:"result",
					width: 550,
					blur:true,
					open:{
						callback: function(){
							var _dialog = this;
							var obj = $("#previewContent",this.pannel);
							Cute.api.get("taobao_item_get",{ num_iid: num_iid },function(json){
								if(json.result.item_get_response){
									Cute.init("core.template",function(){
										var item = json.result.item_get_response.item;
										Cute.api.get("taobao_items_get",{ q:item.title, nicks:item.nick }, function(json2){
											if(json2.result.items_get_response.items){
												var item2 = json2.result.items_get_response.items.item[0];
												$("a.rank",obj).addClass("seller-rank-" + item2.score);
												$(".url_ext",obj).html(Cute.template("URL_PREVIEW_EXT",item2));
											}
										});
										Cute.api.get("taobao_shop_get",{ nick:item.nick }, function(json2){
											if(json2.result.shop_get_response.shop){
												var item2 = json2.result.shop_get_response.shop;
												$("a.nick_link,a.nick_rank",obj).attr("href","http://shop" + item2.sid + ".taobao.com/");
											}
										});
										obj.html(Cute.template("URL_PREVIEW",item));
										_dialog.setPos();
									});
								}else{
									obj.html("无法获取该商品的信息，可能商品信息已过期！");
								}
							},false,true,{
								error:function(){
									obj.html("无法获取该商品的信息，可能商品信息已过期！");
								}
							});
						}
					}
				});
			}else{
				Cute.dialog.alert("没有预览信息，请直接点击完整网址进行查看！");
			}
		},
		buy: function(topicid,postid){
			if(!Cute.common.user.checklogin())return;
			var self = this;
			Cute.dialog.layer("我买过 - 提供购买反馈",{
				content:"#buyDialog",
				mask:true,
				blur:true,
				className:"dialog_like",
				width: 440,
				open:{
					callback:function(){
						var dialog = this;
						$(".buy_detail",this.pannel).empty().append($("#urlItem" + postid).clone().contents().not(".button"));
						$("span.submit_small a",this.pannel).unbind("click").bind("click",function(){
							Cute.api.get("buy",{
								topicid:topicid, 
								postid:postid,
								rate:this.rel
							},function(json){
								dialog.close();
								if(json.code == 1){
									if(this.rel == 1)
										var i = 1;
									else if(this.rel == -1)
										var i = 2;
									$(".meta em","#urlItem" + postid).eq(0).html(function(html){
										return parseInt(html)+1;
									}).end().eq(i).html(function(html){
										return parseInt(html)+1;
									});
									$(self).closest(".button").replaceWith('<span class="btn_buy">已评分</span>');
									Cute.dialog.suggest("提交成功，谢谢参与");
								}else{
									Cute.dialog.suggest(json.result);
								}
							}.bind(this));
							return false;
						});
						//$("span.cancel",this.pannel).unbind("click").bind("click",this.close.bind(this));
					}
				}
			});
		},
		del: function(topicid,postid){
			var self = this;
			Cute.common.confirm("确认要删除这个地址吗？",function(){
				location.replace(self.href);
			});
			return false;
		}
	},
	errorAnimation: function(obj) {
		obj.stop(false, true).focus();
		var _o_bgcolor = obj.css("backgroundColor");
		obj.css({
			backgroundColor: "#FFC8C8"
		}).animate({
			backgroundColor: _o_bgcolor
		}, 1000);
		return false;
	},
	anchor:{
		_init: function(options){
			this.opt = $.extend({
				el: document.body,
				container: document.body,
				target: document.body,
				count: 0,
				max: Cute.MAXANCHORCOUNT,
				maxdesc: 24
			}, options || {});
			this.opt.container = $(this.opt.el).parent();
		},
		init:function(options){
			this._init(options);
			var self = this;
			$.each(self.opt.data.result,function(i,item){
				$('<a href="javascript:void(0)" class="anchor" rel="' + item.id + '" title="' + item.title + '"><span class="icon i_num18">' + (i+1) + '</span></a>').appendTo(self.opt.container).css({
					top: item.anchor.y,
					left: item.anchor.x
				}).hover(function(){
					$("#thingItem" + this.rel).toggleClass("hover");
				});
			});
			$(self.opt.target).children("li").bind("mouseenter mouseleave",function(e){
				//$(this).toggleClass("hover");
				//if(e.type == "mouseenter")$(this).siblings().removeClass("hover");
				self.opt.container.find(".anchor[rel=" + $(this).attr("rel") + "]").andSelf().toggleClass("hover",e.type == "mouseenter");
			});
		},
		bind: function(options){
			this._init(options);
			var self = this;
			self.opt.templete = '<div><div class="d_content">' + 
								'<div class="wedge"></div>' + 
								'<form>' + 
								'<input class="text default" type="text" name="content" value="物品描述（如：品牌、亮点）..." autocomplete="off"" />' + 
								'<span class="button submit"><span><button type="submit">保存锚点</button></span></span> ' + 
								'<a href="javascript:;" class="del_anchor">移除</a>' + 
								'</form>' + 
							  '</div>';
			if(self.anchorDialog == undefined) {
				self.anchorDialog = Cute.dialog.layer(null,{
					content: self.opt.templete,
					className:"tooltip anchor_form",
					width: 340,
					open:{
						callback:function(){
							var initValue = $("li",self.opt.target).eq(this.pannel.data("index") - 1).children("kbd").text().trim();
							if(initValue.length > 0){
								self.anchorDialog.pannel.find("input[name=content]").focus().val(initValue)[0].select();
							}else if(self.opt.a_count >= 1){
								self.anchorDialog.pannel.find("input[name=content]").focus();
							}
						}
					}
				}).hide();
				self.anchorDialog.pannel.find("form").bind("submit.anchor",function(){
					var desc = this.pannel.find("input[name=content]");
					var position = $(".anchor:eq(" + (this.pannel.data("index") - 1) + ")",self.opt.container).position();
					if(Cute.form.isInputNull(desc)){
						alert("请填写物品描述！");
						return false;
					}
					if(Cute.tools.string.length(desc.val()) > self.opt.maxdesc){
						alert("物品描述最多只允许" + self.opt.maxdesc + "个字符（" +  self.opt.maxdesc / 2 + "个中文）哦。");
						desc.focus();
						return false;
					}
					self.save(0,this.pannel.data("index"),desc.val().trim(),parseInt(position.left,10),parseInt(position.top,10));
					return false;
				}.bind(self.anchorDialog));
				self.anchorDialog.pannel.find("a.del_anchor").bind("click.anchor",function(){
					self.delTmp(this.pannel.data("index"));
					return false;
				}.bind(self.anchorDialog));
			}
			$(self.opt.el).bind("click",self.mark.bind(this)).out("click",function(e){
				if(e.target.tagName == "INPUT" || e.target.tagName == "TEXTAREA") return;
				var a = $(".anchor",self.opt.container);
				if(a.has(e.target).length == 0 && self.anchorDialog.pannel.has(e.target).length == 0){
					var desc = self.anchorDialog.pannel.find("input[name=content]");
					if(Cute.form.isInputNull(desc)){
						self.anchorDialog.hide();
						self.opt.count = $("li",self.opt.target).length;
						a.slice(self.opt.count).remove();
					}else{
						self.anchorDialog.pannel.find("form").triggerHandler("submit.anchor");
					}
				}
				return false;
			},true);
		},
		_initDialog: function(){
			if(this.anchorDialog){
				this.anchorDialog.hide();
			}
		},
		mark: function(e,defaultX,defaultY){
			var self = this;
			self.opt.count = $("li",self.opt.target).length;
			if(self.opt.count >= self.opt.max){
				Cute.dialog.notice("最多只允许标记" + self.opt.max + "个锚点！",{ className:"dialog_error"});
				return false;
			}
			self.delTmp(self.opt.count + 1);
			self.bindMark.call(self,defaultX || ((e.layerX||e.offsetX) - 9),defaultY || ((e.layerY||e.offsetY) - 9), true).triggerHandler("click");
		},
		bindMark: function(x,y,issave,userid,postcount){
			if(postcount == undefined) postcount = 0;
			if(userid == undefined) userid = 0;
			var self = this;
			self.opt.a_count = $(".anchor",self.opt.container).length;
			var obj = $('<a href="javascript:void(0)" class="anchor preview" title="' + (issave ? "标记可拖动进行位置调整" : "已保存标记不允许移动") + '"><span class="icon i_num18">' + (self.opt.a_count + 1) + '</span></a>').appendTo(self.opt.container).css({
				top: y,
				left: x
			}).bind("mouseenter mouseleave",function(){
				var index = $(this).index() - 1;
				$("li:eq(" + index + ")",self.opt.target).toggleClass("hover");
			}).bind("mousedown",function(){
				self.anchorDialog.hide();
				if(issave) $(this).css("opacity",0.5);
			}).bind("mouseup",function(){
				$(this).css("opacity",1);
			});
			if(Cute.common.user.info.groupid == 1 || userid == 0 || (Cute.common.user.info.userid == userid && postcount == 0)){
				obj.bind("click",function(e){
					self._initDialog();
					self.anchorDialog.setPos({
						top: $(this).offset().top - 10,
						left: $(this).offset().left + 30
					}).pannel.data("index",$(this).index());
					self.anchorDialog.show();
					e.preventDefault();
					e.stopPropagation();
					return false;
				});
				if(issave)
					obj.drag(self.opt.container);
			}
			return obj;
		},
		delTmp: function(i){
			var self = this;
			self.anchorDialog.hide();
			$("li",self.opt.target).eq(i-1).remove();
			$(".anchor",self.opt.container).eq(i-1).remove();
			var _count = $("li",self.opt.target).length;
			if(self.opt.count > _count){
				self.opt.count = _count;
				self.opt.a_count = $(".anchor",self.opt.container).length;
				$(".anchor",self.opt.container).each(function(i){
					$(".i_num18",this).html(i+1);
					$("li:eq(" + i + ") .i_num23",self.opt.target).html(i+1);
				});
			}
		},
		save: function(id,i,value,x,y,userid,postcount){
			var self = this;
			if(postcount == undefined) postcount = 0;
			if(userid == undefined) userid = 0;
			if($("li",self.opt.target).eq(i - 1).length == 0){
				var _html = [];
				_html.push('<li><span class="icon i_num23">' +  i + '</span><kbd>' + value + '</kbd>');
				if(Cute.common.user.info.groupid == 1 || Cute.common.user.info.userid == userid || userid == 0){
					if(Cute.common.user.info.groupid == 1 || postcount == 0)
						_html.push('<a href="javascript:void(0)" class="remove" title="删除" unselectable="on"></a>');
					else
						_html.push('<em class="note" title="出于对购买信息提供者的权益保护，我们希望不删除任何一个已有相应购买地址的标记，如需删除，请联系DoCute客服。">锁</em>');
				}else{
					_html.push(' <em class="date">（他人标记）</em>');
				}
				_html.push('<input type="hidden" name="anchorid" value="' + (id || 0) + '" />');
				_html.push('<input type="hidden" name="anchors" value="' + value + '" />');
				_html.push('<input type="hidden" name="signs" value="' + x + ',' + y + '" />');
				_html.push('<input type="hidden" name="postcount" value="' + postcount + '" />');
				_html.push('</li>');
				$(_html.join('')).appendTo(self.opt.target)
					.bind("mouseenter mouseleave",function(){
						var index = $(this).index();
						$("a.anchor:eq(" + index + ")",self.opt.container).toggleClass("hover");
					}).click(function(e){
						var index = $(this).index();
						$(".anchor:eq(" + index + ")",self.opt.container).triggerHandler("click");
						e.preventDefault();
						e.stopPropagation();
						return false;
					}).find(".remove").click(function(e){
						//Cute.common.confirm("确认要删除吗？",function(){
							self.delTmp($(this).closest("li").index() + 1);
						//}.bind(this));
						e.preventDefault();
						e.stopPropagation();
						return false;
					});
				self.opt.count = $("li",self.opt.target).length;
			}else{
				$("li",self.opt.target).eq(i - 1).find("kbd").text(value).end()
					.find("input[name=anchors]").val(value).end()
					.find("input[name=signs]").val(x + ',' + y);
			}
			this.anchorDialog.pannel.find("input.text").val("").trigger("blur");
			this._initDialog();
		},
		edit: function(topicid, anchorid){
			Cute.dialog.layer("修改物品标记",{
				content: "#anchorEditDialog",
				mask:true,
				open:{
					callback:function(){
						var dialog = this;
						$("input[name=title]",this.pannel).val($("kbd","#thingTitle" + anchorid).html());
						$("span.submit_small a",this.pannel).unbind("click").eq(0).bind("click",function(){
							$("form",dialog.pannel).trigger("submit");
							return false;
						});
						$("form",this.pannel).submit(function(){
							var self = this;
							var titleValue = $("input[name=title]",dialog.pannel).val();
							if(titleValue.trim() == ""){
								alert("描述不能为空！");
								return false;
							}
							dialog.close();
							var loading = Cute.dialog.loading();
							Cute.api.post("updateanchor",{
								title: titleValue,
								anchorid: anchorid
							}, function(json){
								if(json.code == 1){
									location.reload();
								}else{
									Cute.dialog.alert(json.result);
								}
							});
							return false;
						}).find("a.del_anchor").bind("click",function(){
							if(confirm("确认要移除吗？")){
								dialog.close();
								var loading = Cute.dialog.loading();
								Cute.api.get("deleteanchor",{
									anchorid: anchorid
								}, function(json){
									if(json.code == 1){
										location.reload();
									}else{
										loading.close();
										Cute.dialog.alert(json.result);
									}
								});
							}
							return false;
						});
						//$("span.cancel",this.pannel).unbind("click").bind("click",this.close.bind(this));
					}
				}
			});
		}
	},
	comment:{
		init: function(obj,topicid){
			obj = $(obj);
			//评论
			$("span.comment_reply_btn a",obj).click(function(){
				$("form.thread_form input[name=parentid]",obj).val(this.rel);
				$("form.thread_form textarea[name=content]",obj).focus().val(this.title);
				return false;
			});
			$("a.comment_del_btn",obj).live("click",function(){
				Cute.common.comment.del(this.rel,topicid);
				return false;
			});
			$("form.thread_form textarea[name=content]",obj).focus(function(){
				if(this.timer) return;
				this.timer = setInterval(function(){
					if(!/^@[^\ ]+\ .*/.test($(this).val())){
						$("form.thread_form input[name=parentid]",obj).val(0);
					}
				}.bind(this),200);
			}).blur(function(){
				clearInterval(this.timer);
			});
			Cute.common.comment.bindEmot($("form.thread_form .i_insertemot",obj),$("form.thread_form textarea[name=content]",obj));
			$("form.thread_form",obj).submit(function(){
				var obj = $("textarea[name=content]",this);
				var parent = $("input[name=parentid]",this);
				if (Cute.form.isInputNull(obj)) {
					Cute.common.errorAnimation(obj);
					return false;
				}
				Cute.common.comment.save({
					target: parent,
					topicid: topicid,
					parentid: parent.val(),
					content: obj.val()
				},function(json){
					if(!json.code > 0) return;
					obj.val("");
					if(parent.val() == 0){
						var template = '<li class="item" style="display:none">\
											<a href="javascript:void(0)" class="comment_del_btn" rel="' + json.code + '" title="删除">X</a>\
											<div class="list_image">\
												<a href="/user/' + Cute.common.user.info.userid + '/" title="' + Cute.common.user.info.nickname + '"><img alt="' + Cute.common.user.info.nickname + '" onerror="this.src=\'' + Cute.RESOURCEURL + '/avatar/noface.jpg\'" class="icon i_user i_user50" src="' + Cute.RESOURCEURL + '/avatar/' + Cute.common.user.info.userid + '/' + Cute.common.user.info.userid + '_1.jpeg"></a>\
												<a class="title" href="/user/' + Cute.common.user.info.userid + '/">' + Cute.common.user.info.nickname + '</a>\
												<em class="date">刚刚</em>\
											</div>\
											<div class="list_info"><p>' + json.result + '</p></div>\
										</li>';
						$("li.nodata","#comment").remove();
						$(template).appendTo("#comment .list_comment").fadeIn(1000);
					}else{
						var template = '<li style="display:none">\
											<a href="javascript:void(0)" class="comment_del_btn" rel="' + json.code + '" title="删除">X</a>\
											<div class="lite_image">\
												<a href="/user/' + Cute.common.user.info.userid + '/" title="' + Cute.common.user.info.nickname + '"><img alt="' + Cute.common.user.info.nickname + '" onerror="this.src=\'' + Cute.RESOURCEURL + '/avatar/noface.jpg\'" class="icon i_user i_user30" src="' + Cute.RESOURCEURL + '/avatar/' + Cute.common.user.info.userid + '/' + Cute.common.user.info.userid + '_2.jpeg"></a>\
												<a class="title" href="/user/' + Cute.common.user.info.userid + '/">' + Cute.common.user.info.nickname + '</a>\
												<em class="date">刚刚</em>\
											</div>\
											<div class="lite_info"><p>' + json.result + '</p></div>\
										</li>';
						$(template).appendTo($(".lite_small_comment","#comment" + parent.val()).show()).fadeIn(1000);
						location.href = "#comment" + parent.val();
					}
					Cute.dialog.suggest("评论成功！");
					parent.val(0);
				});
				return false;
			});
		},
		del:function(commentid,topicid){
			Cute.common.confirm("你确认要删除这条评论吗？",function(){
				Cute.api.get("deletecomment",{
					id: commentid,
					topicid: topicid
				},function(json){
					if(json.code == 1){
						$("#comment" + commentid).slideUp(1000,function(){
							$(this).remove();
						});
					}else{
						Cute.dialog.notice(json.result);
					}
				});
			});
			return false;
		},
		bindEmot: function(el,target){
			var $div = $('<div class="d_emot d_content"></div>');
			el = $(el);
			target = $(target);
			el.click(function(){
				if(el.emot){
					el.emot.toggle();
				}else{
					for(var i = 1; i <= 20; i++){
						$('<a rel="' + i + '" class="emot e-base-' + i + '" href="javascript:;"><img alt="" src="' + Cute.RESOURCEURL + '/images/common/emot/' + i + '.gif"></a>').appendTo($div).click(function(){
							Cute.tools.insertSelection(target[0], '[em' + this.rel + ']');
							el.emot.hide();
							target.focus().css("color", "#000");
							return false;
						});
					}
					el.emot = Cute.dialog.tooltip("layer", "", {
						width: 200,
						content: $("<div/>").append($div),
						pos: {
							"top": el.offset().top + el.outerHeight() + 2,
							"left": el.offset().left - 1
						}
					})
				}
				return false;
			});
		},
		save: function(options, callback){
			var opt = $.extend({
				topicid: 0,
				partneid: 0,
				content: ""
			}, options || {});
			callback = callback || $.noop;
			Cute.api.post("postcomment",{
				topicid: opt.topicid,
				parentid: opt.parentid,
				content: opt.content
			},function(json){
				if(json.code > 0){
					callback(json);
				}else{
					Cute.dialog.notice(json.result,{ className:"dialog_error"});
				}
			});
		}
	},
	like: {
		save:function(topicid,tags, callback){
			Cute.api.post("like",{
				topicid: topicid,
				tags: tags || []
			}, function(json){
				if(json.code == 1){
					$("var","#likeinfo" + topicid).html(json.result);
					if($.isFunction(callback))callback(json.result);
				}else{
					Cute.dialog.notice(json.result,{ className:"dialog_error"});
				}
			});
			return false;
		},
		show: function(topicid,authorid, reload){
			var self = this;
			if(authorid == Cute.common.user.info.userid){
				Cute.dialog.notice("不能给自己发表的图片投票哦！",{ className:"dialog_error"});
				return false;
			}
			var obj = $("#likeinfo" + topicid);
			self.save(topicid, []);
			if(!obj.data("isshow")){
				var dialog = Cute.dialog.tooltip("ajax",null,{
					action:"write",
					params:{
						name: 1,
						topicid: topicid
					},
					width: 580,
					className:"tooltip like_dialog",
					drag: false,
					pos:{
						top: obj.offset().top + obj.height() + 2,
						left: obj.offset().left
					},
					mask: false,
					open:{
						callback:function(){
							obj.data("isshow",true);
							var _dialog = this;
							var isedit = false;
							$("ul.tag_label li>a",this.pannel).bind("click.tag",function(){
								isedit = true;
								if(!$("input[name=tag]",this).is(":checked") && $("input[name=tag]:checked",_dialog.pannel).length >= Cute.MAXTAGCOUNT){
									alert("最多只能选择 " + Cute.MAXTAGCOUNT + " 个风格印象标签哦！");
									return false;
								}
								$(this).toggleClass("curr").find("input:checkbox").attr("checked",$(this).hasClass("curr"));
								return false;
							});
							$("span.submit a",this.pannel).click(function(){
								var _tags = $("input[name=tag]",this.pannel).serializeArray();
								var tags = [];
								$.each(_tags, function(i,item){
									tags.push(item.value);
								});
								self.save(topicid, tags ,function(){
									//if(reload && isedit) location.reload();
									_dialog.close();
								});
								return false;
							}.bind(this));
							$("span.cancel a",this.pannel).click(this.close.bind(this));
						}
					},
					close:{
						callback:function(){
							obj.removeData("isshow");
						}
					}
				});
			}
			return false;
		}
	},
	votetag:function(tagid,topicid,rate){
		
	},
	user: {	
		checklogin: function(){
			if(!Cute.common.user.info.userid){
				Cute.dialog.layer("请先登录",{
					content:'<div><div class="d_content">对不起，您还没有登录呢！</div></div>',
					className: "dialog_error",
					mask:true,
					buttons: [{
						title: '马上登录',
						type: 'main',
						close: true,
						func: function(){
							location.href = $("#loginLink").attr("href");
						}
					},
					{
						title: '注册新帐号',
						type: 'button_blue',
						close: true,
						func: function(){
							location.href = $("#regLink").attr("href");
						}
					}
					]
				});
				return false;
			}
			return true;
		},
		//好友
		follow: function(uid, options) {
			var options = $.extend({
				el: null,
				displayname: ""
			}, options);
			var _loading = Cute.dialog.loading();
			Cute.api.get("addfollow", { uid: uid }, function(json) {
				Cute.dialog.notice(json.result, { className:"dialog_succes"});
				switch (json.code) {
					case 1:
						if (options.el) $(options.el).attr("onclick", "").removeClass().addClass("disabled").html('已成功关注');
						break;
				}
				_loading.close();
			});
		},
		unfollow: function(uid, options) {
			var options = $.extend({
				el: null,
				displayname: ""
			}, options);
			var _loading = Cute.dialog.loading();
			Cute.api.get("removefollow", { uid: uid }, function(json) {
				Cute.dialog.notice(json.result, { className:"dialog_succes"});
				switch (json.code) {
					case 1:
						if (options.el) $(options.el).attr("onclick", "").removeClass().addClass("disabled").html('已取消关注');
						break;
				}
				_loading.close();
			});
		},
		editIcon: function(){
			var imgw,imgh;
			this.preview = function(img, selection) { 
				var scale50X = 50 / selection.width; 
				var scale50Y = 50 / selection.height; 
				var scale30X = 30 / selection.width; 
				var scale30Y = 30 / selection.height; 
				$('#preimg50').css({ 
					width: Math.round(scale50X * imgw) + 'px', 
					height: Math.round(scale50Y * imgh) + 'px', 
					marginLeft: '-' + Math.round(scale50X * selection.x1) + 'px',
					marginTop: '-' + Math.round(scale50Y * selection.y1) + 'px'
				});
				$('#preimg30').css({ 
					width: Math.round(scale30X * imgw) + 'px', 
					height: Math.round(scale30Y * imgh) + 'px', 
					marginLeft: '-' + Math.round(scale30X * selection.x1) + 'px',
					marginTop: '-' + Math.round(scale30Y * selection.y1) + 'px'
				});
				if($('#imgpos').length && selection) $('#imgpos').attr('value',selection.x1 + '_' + selection.y1 + '_' + (selection.x2 - selection.x1)).attr('name', 'imgpos');
			}
			if($('#imgpos').length){
				imgw = $('#bigimg').width();
				imgh = $('#bigimg').height();
				var _ = $('#imgpos').val().split('_');
				var pos = (_[2] && (_[2] != '0') && (parseInt(_[0]) + parseInt(_[2])) <= imgw && (parseInt(_[1]) + parseInt(_[2])) <= imgh)?  { 
					x1: parseInt(_[0]), 
					y1: parseInt(_[1]), 
					x2: parseInt(_[0]) + parseInt(_[2]), 
					y2: parseInt(_[1]) + parseInt(_[2]) 
				} : {
					x1: imgw > imgh ? (imgw-imgh)/2+3 : (imgw == imgh ? 0 : 3), 
					x2: imgw > imgh ? (imgw+imgh)/2-3 : (imgw == imgh ? imgw : imgw-3), 
					y1: imgw > imgh ? 3 : (imgw == imgh ? (imgh-imgw)/2 : (imgh-imgw)/2 + 3), 
					y2: imgw > imgh ? imgh-3 : (imgw == imgh ? (imgh+imgw)/2 : (imgh+imgw)/2-3) 
				};
				$('#bigimg').imgAreaSelect($.extend(pos,{
					aspectRatio : '1:1' ,
					onSelectChange : this.preview,
					onInit : this.preview,
					persistent : true
				}));
			}
		}
	},
	message: {
		filter: function(id){
			Cute.api.get("readnotice",{
				id: id,
				status: 2
			},function(json){
				if(json.code == 1){
					$(this).closest("tbody").fadeOut(function(){
						if($(this).siblings().length == 0) 
							$(".index_notice2").remove();
						else
							$(this).remove();
					});
				}else{
					Cute.dialog.notice(json.result);
				}
			}.bind(this));
		},
		post: function(touid, touname) {
			Cute.dialog.ajax("给" + touname + "发送悄悄话", {
				action: "write",
				params: {
					id: 1
				},
				result: "result",
				open: {
					callback: function() {
						this.pannel.find("textarea[name=content]").focus();
					}
				},
				buttons: [{
					title: '提交',
					type: 'main',
					close: false,
					func: function() {
						var obj = this.pannel.find("textarea[name=content]");
						if (Cute.form.isInputNull(obj)) {
							Cute.SNS.common.errorAnimation(obj);
							return false;
						}
						this.close();
						Cute.api.post("postmessage", {
							touid: touid,
							messagebody: obj.val()
						}, function(json) {
							if (json.code > 0) {
								Cute.dialog.notice(json.result, { className:"dialog_succes"});
							}
						});
					}
				},
					{
						title: '取消',
						type: 'cancel',
						close: true
					}
					]
			});
		},
		check: function() {
			var _this = this;
			_this.originalTitle = _this.originalTitle || document.title;
			var mainObj = $("#container");
			var noticeTips = $("#noticeTips");
			$(window).bind("resize.checkmsg",function(){
				noticeTips.css("right",mainObj.offset().left);
			}).triggerHandler("resize.checkmsg");
			Cute.api.get("checknotice", {}, function(json) {
				if (json.code > 0) {
					if (json.result.length > 0) {
						noticeTips.show().find("em").html(json.result.length);
						clearInterval(_this.timer);
						_this.timer = setInterval(function() {
							if (!this.tipSwitch) {
								this.tipSwitch = true;
								//document.title = "【新消息】" + this.originalTitle;
								 $("a>span",noticeTips).css("visibility","visible");
							} else {
								this.tipSwitch = false;
								$("a>span",noticeTips).css("visibility","hidden");
								//document.title = "【　　　】" + this.originalTitle;
							}
						} .bind(_this), 700);
					} else {
						clearInterval(_this.timer);
						noticeTips.hide().find("em").html(0);
						document.title = _this.originalTitle;
						_this.originalTitle = "";
					}
				}
			}, false, true, {
				global: false
			});
			setTimeout(arguments.callee.bind(this), Cute.NOTICEFREQUENCY);
		}
	}
};

/*
 * jQuery Color Animations
 */
(function(jQuery){
	jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		jQuery.fx.step[attr] = function(fx){
			if ( fx.state == 0 ) {
				fx.start = getColor( fx.elem, attr );
				fx.end = getRGB( fx.end );
			}
			fx.elem.style[attr] = "rgb(" + [
				Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
			].join(",") + ")";
		}
	});
	function getRGB(color) {
		var result;
		if ( color && color.constructor == Array && color.length == 3 )
			return color;
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];
		return "";
	}
	function getColor(elem, attr) {
		var color;
		do {
			color = jQuery.curCSS(elem, attr);
			if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
				break; 
			attr = "backgroundColor";
		} while ( elem = elem.parentNode );
		return getRGB(color);
	};
})(jQuery);
