jQuery.fn.tucao = function(opts){
	opts = jQuery.extend({
		auto_play:true,//是否自动播放
		play_delay:5000,//延迟自动播放
		play_tick:3000,//冒泡时间间隔
		opacity:0.8,//透明度
		buffer:3,//缓存几页
		object_type:'comic',
		object_id:0,
		total_tucao:0,
		callback:function(){}
	},opts||{});
	
	var bar_html='<div style="width: 840px;" class="toso_button">';
	bar_html+='<div class="toso_button_content">';
	bar_html+='<span class="bg_yellow"><a href="###" class="btn_bg"></a>';
	bar_html+='<div class="toso_bg_hover" style="display:none;" value="0"><a href="###" class="yellow" value="0">黄　　色</a><a href="###" class="pink" value="1">粉　　色</a><a href="###" class="blue" value="2">蓝　　色</a><a href="###" class="no" value="3">无边透明</a><a href="###" class="no_white" value="4">无边白色</a><a href="###" class="no_black" value="5">无边黑色</a></div>';	
	bar_html+='</span>';
	bar_html+='<span class="font_black"><a href="###" class="btn_font"></a>';
	bar_html+='<div class="toso_font_hover" style="display:none;" value="0"><a href="###" class="yellow" value="2">黄　色</a><a href="###" class="red" value="3">红　色</a><a href="###" class="green" value="4">绿　色</a><a href="###" class="blue" value="5">蓝　色</a><a href="###" class="white" value="1">白　色</a><a href="###" class="black" value="0">黑　色</a></div>';
	bar_html+='</span><span class="textarea_left"></span><span class="textarea_right">';
	bar_html+='<input type="text" onfocus="$().data(\'can_left_right\',false);" onblur="$().data(\'can_left_right\',true);" style="width: 224px;" class="textarea input_tucao" value="这里可以输入你想要吐槽的话哦！" onclick="if(this.value==\'这里可以输入你想要吐槽的话哦！\') this.value=\'\'" maxlength="200"/></span><span><a href="###" class="btn_toso"></a></span>';
	bar_html+='<span><a href="###" class="btn_pre" title="上一批吐槽"></a></span><span><a href="###" class="btn_stop" title="播放/暂停"></a></span>';
	bar_html+='<span><a href="###" class="btn_next" title="下一批吐槽"></a></span><span><a href="###" class="btn_show" title="隐藏吐槽/显示吐槽"></a></span>';
	bar_html+='<span class="explain"><span class="total_tucao">妖子们赶快来吐槽吧！</span></span>';
	bar_html+='</div>';
	bar_html+='</div>';
	
	function showSlide(btn,panel){
		$(btn).unbind().bind("click",function(){
			$(btn).blur();
			$(panel).fadeIn("fast");
			if($(btn).data('time')) clearTimeout($(btn).data('time'));
			if($(panel).data('time')) clearTimeout($(panel).data('time'));
		}).bind("mouseleave",function(){
			hidequcikmenu=setTimeout(function(){$(panel).fadeOut("fast");},200);
			$(btn).data('time',hidequcikmenu);
		});
		$(panel).unbind().bind("mouseleave",function(){
			hidequcikmenu=setTimeout(function(){$(panel).fadeOut("fast");},200);
			$(panel).data('time',hidequcikmenu);
		}).bind("mouseenter",function(){
			if($(btn).data('time')) clearTimeout($(btn).data('time'));
			if($(panel).data('time')) clearTimeout($(panel).data('time'));		
		}).find("a").click(function(){
			$(this).blur();
			$(panel).fadeOut("fast");
		});			
	}
	
	return this.each(function() {
		var user_setting=get_user_setting();
		var panel = jQuery(this);
		var object_id = panel.attr('object_id');
		var object_type = panel.attr('object_type');
		if(object_id==null || object_type==null) return;
		var width = panel.width();
		var height = panel.height();
		var bar = $(bar_html);
		var panel_bg_hover = bar.find('.toso_bg_hover');
		var panel_font_hover = bar.find('.toso_font_hover');
		var btn_bg = bar.find('.btn_bg');
		var btn_font = bar.find('.btn_font');
		var btn_send = bar.find('.btn_toso');
		var btn_prev = bar.find('.btn_pre');
		var btn_next = bar.find('.btn_next');
		var btn_play = bar.find('.btn_stop');
		var btn_show = bar.find('.btn_show');	
		var input = bar.find('.input_tucao');
		var panel_total = bar.find('.total_tucao');
		var is_play=false;
		var is_show=true;
		var is_loading=false;
		var page_size = parseInt(width*height/3/(15000));
		//alert(page_size);
		if(page_size<2) page_size=2;
		var first_t = null;
		var last_t = null;
		var list=[];
		var old_play=is_play;
		var zIndex=10;
		var user=null;
		var top_offest=19;
		
		//如果小于300*400则不开启吐槽
		if(width<300 || height<400){
			panel.after('<div class="toso_button" style="width: 820px;"><div class="toso_button_content" style="line-height:45px;color:#333;">图片宽度小于300或者高度小于400则不开放吐槽功能</div></div>');
			return;
		}
		
		//=====初始化事件开始
		//背景事件
		panel_bg_hover.find('a').click(function(){
			user=get_user();
			if(user!=null && (user.group_user==1 || user.group_user==2)){
				panel_bg_hover.attr('value',$(this).attr('value'));
				btn_bg.parent().attr('class','bg_'+$(this).attr('class'));
			}else{
				showMsg('VIP会员才能切换背景和字体颜色!<br/><a style="color:blue" href="'+cfg_host_base()+'/z/help/vip_member.html" target="_blank">什么是VIP会员？</a>');
			}
		});
		showSlide(btn_bg,panel_bg_hover);
		//字体事件
		panel_font_hover.find('a').click(function(){
			user=get_user();
			if(user!=null && (user.group_user==1 || user.group_user==2)){
				panel_font_hover.attr('value',$(this).attr('value'));
				btn_font.parent().attr('class','font_'+$(this).attr('class'));
			}else{
				showMsg('VIP会员才能切换背景和字体颜色!<br/><a style="color:blue" href="'+cfg_host_base()+'/z/help/vip_member.html" target="_blank">什么是VIP会员？</a>');
			}
		});	
		showSlide(btn_font,panel_font_hover);
		//吐槽事件
		btn_send.click(function(e){$(this).blur(); send(e);});
		//上一页事件
		btn_prev.click(function(){$(this).blur(); prev_page();});
		//下一页事件
		btn_next.click(function(){$(this).blur(); next_page();});
		//播放暂停按钮事件
		btn_play.click(function(){$(this).blur(); if(is_play){stop();}else{play();} });
		//显示隐藏事件
		btn_show.click(function(){$(this).blur(); if(is_show){hide();}else{show();} });

		user=get_user();
		
		flush_total_tucao(opts.total_tucao);
		
		//播放事件
		setTimeout(function(){
			is_play=true;
		},opts.play_delay);
		setInterval(function(){
			if(is_play && is_show && opts.total_tucao>0){
				next();
			}
		},opts.play_tick);
		//======初始化事件结束
		
		if(user_setting!=null && user_setting['tucao']=='0'){
			hide();
		}
		
		
		
		function flush_total_tucao(total_tucao){
			opts.total_tucao=total_tucao;
			panel_total.html('共有'+total_tucao+'个吐槽，欢迎大家吐槽');
		}
		
		function reset(){
			list=[];
			first_t=last_t=null;
			user=get_user();
			zIndex=10;
		}
		
		function play(){
			if(!is_show) show();
			old_play=is_play;
			is_play=true;
			btn_play.addClass('btn_stop').removeClass('btn_play');
		}
		
		function stop(){
			old_play=is_play;
			is_play=false;
			btn_play.addClass('btn_play').removeClass('btn_stop');
		}
		
		function show(){
			set_user_setting('tucao','1');
			is_show=true;
			btn_show.addClass('btn_show').removeClass('btn_hide');
			if(old_play)
				play();
			$('.toso_dialogue').show();
		}
		function hide(){
			set_user_setting('tucao','0');
			is_show=false;
			old_play=is_play;
			btn_show.addClass('btn_hide').removeClass('btn_show');
			if(old_play)
				stop();
			$('.toso_dialogue').hide();
		}
		
		function get_tucao_width(content){
			var el=$('<span style="display:none">'+content+'</span>');
			$('body').append(el);
			var width=el.width();
			el.remove();
			return width;
		}
		
		function send(e){
			user=get_user();
			if(user==null) {login_ajax();return;}
			if(is_loading) return;
			if(!is_show) show();
			if(is_play) stop();
			var content = input.val();
			if(content==null || content.length==0 || content=='这里可以输入你想要吐槽的话哦！'){
				showMsg('请输入吐槽内容');return;
			}
			is_loading=true;
			var send_back=panel_bg_hover.attr('value');
			var send_color=panel_font_hover.attr('value');
			var send_w=get_tucao_width(content);
			var send_h=(parseInt(send_w/250)+1)*20+10;
			send_w+=12;//修正边框
			if(send_w>250) send_w=250;
			var send_step=0;
			//让全部的吐槽消失
			remove_all_tucao();
			panel.append('<div class="send_over" style="z-index:9999;position:absolute;top:0;left:0;width:'+width+'px;height:'+height+'px;background-color:#000;filter:alpha(opacity=30); opacity:0.3"></div>');
			var mpos=mouseCoords(e);
			var ipos=panel.offset();
			var cursor='<div id="tucao_cursor" class="toso_cursor" style="top:'+mpos.y+'px;left:'+mpos.x+'px"></div>';
			$(document).bind('keydown',function(evt){
				evt = evt ||window.event;
				var key=evt.which||evt.keyCode;
				if (key == 27){
					$('body').unbind('click').unbind('mousemove');
					$(document).unbind('keydown');
					$('#tucao_cursor').remove();
					panel.find('.send_over').remove();
					is_loading=false;
				}
			});
			$('body').append(cursor);
			$('body').bind('mousemove',function(e){
				mpos=mouseCoords(e);
				var x=mpos.x-ipos.left;
				var y=mpos.y-ipos.top;
				var cur=$('#tucao_cursor');
				if(x<0 || x>width || y<0 || y>height) {
					cur.addClass('toso_cursor_no');	
				}else{
					cur.removeClass('toso_cursor_no');
				}
				cur.css('top',mpos.y).css('left',mpos.x);
			}).bind('click',function(e){
				if(send_step==0){ send_step++;return;};
				if(send_step==2) 
				
				mpos=mouseCoords(e);
				
				var x=mpos.x-ipos.left;
				var y=mpos.y-ipos.top;
				if(x<0 || x>width) {
					//showMsg('请把吐槽放至图片区域内！');
					return;
				}
				if(y<0 || y>height){
					//showMsg('请把吐槽放至图片区域内！');
					return;
				}
				send_step++;
				$('body').unbind('click').unbind('mousemove');
				$(document).unbind('keydown');
				//alert(x+','+y);
				$('#tucao_cursor').remove();
				panel.find('.send_over').remove();
				//return;
				$.ajax({
					url:'/www/ajax.php?mod=tucao&act=send_tucao',
					type:'POST',
					data:{x:x,y:y,w:send_w,h:send_h,content:content,color:send_color,back:send_back,object_type:opts.object_type,object_id:opts.object_id},
					dataType:'json',
					cache:false,
					success:function(o){
						is_loading=false;
						input.val('');
						showMsg(o.message);
						reset();
						next_page();
						flush_total_tucao(opts.total_tucao+1);
					},error:function(){
						is_loading=false;
						showMsg('通讯错误请稍后再试');
					}
				});			
			});
		}

		
		//下一个（自动播放）
		function next(){
			if(is_loading) return;
			is_loading=true;
			if(list.length==0 || list[list.length-1].tucao_id==last_t.tucao_id){
				get_list(page_size,'next')	
			}else{
				count=$('.toso_dialogue').length;
				for(i=0;i<list.length;i++){
					if(count>=page_size && first_t.tucao_id==list[i].tucao_id){
						remove_tucao(list[i]);
						first_t=list[i+1];
						break;
					}					
				}
				for(i=0;i<list.length;i++){
					if(last_t.tucao_id==list[i].tucao_id){
						show_tucao(list[i+1]);
						last_t=list[i+1];
						break;
					}
				}
				is_loading=false;
			}
		}
		
		function next_page(){
			if(is_loading) return;
			is_loading=true;
			if(!is_show) show();
			if(is_play) stop();
			var count=0;
			for(i=0;i<list.length;i++){
				count++;
				if(last_t.tucao_id==list[i].tucao_id){
					break;
				}
			}
			if(list.length-count<page_size){
				get_list(page_size,'next_page')	
			}else{
				remove_all_tucao();
				last_i=-1;
				for(i=0;i<list.length;i++){
					if(last_t.tucao_id==list[i].tucao_id){
						last_i=i;
					}
				}
				if(last_i>=-1){
					for(i=last_i+1;i<list.length && i<last_i+1+page_size;i++){
						if(i==last_i+1)
							first_t=list[i];
						show_tucao(list[i]);
						last_t=list[i];
					}
				}
				is_loading=false;
			}
		}
		
		function prev_page(){
			if(is_loading) return;
			is_loading=true;
			if(!is_show) show();
			if(is_play) stop();
			var count=0;
			for(i=0;i<list.length;i++){
				if(first_t.tucao_id==list[i].tucao_id){
					break;
				}
				count++;
			}			
			if(count<page_size){
				get_list(page_size,'prev_page')	
			}else{
				remove_all_tucao();
				first_i=-1;
				if(first_t==null){
					first_i=list.length;
				}else{
					for(i=list.length-1;i>=0;i--){
						if(first_t.tucao_id==list[i].tucao_id){
							first_i=i;break;
						}
					}
				}
				if(first_i>0){
					for(i=first_i-1;i>=0 && i>first_i-1-page_size;i--){
						if(i==first_i-1)
							last_t=list[i];
						show_tucao(list[i]);
						first_t=list[i];
					}
				}
				is_loading=false;
			}
		}
		
		function get_right(t){
			if(user!=null && user.id==t.user_id ){//这里还要加一个管理员删除
				return true;
			}
			return false;
		}
		
		function show_tucao(t){
			yy=t.y-top_offest;
			zIndex++;
			var max_w=get_tucao_width(t.content);
			max_w+=t.back>2?20:22;
			min_w=parseInt(max_w/19)+16;
			min_w=min_w<22?22:min_w;
			max_w=max_w>250?250:max_w;
			var right=get_right(t);
			var title='';
			if(t.user_id>0){
				title=t.nickname+' 吐槽于 '+t.time;
			}else{
				title='有妖气网友吐槽于 '+t.time;
			}	
			font_color=['black','white','yellow','red','green','blue'];
			bg_color=['yellow','pink','blue','no','no_white','no_black'];
			opacity=t.back>2?'filter:alpha(opacity=100); opacity:1;':'filter:alpha(opacity='+opts.opacity*100+'); opacity:'+opts.opacity+';';
			if(right===false){
				el=$('<div id="tucao_'+t.tucao_id+'" style="'+opacity+'display:none;float:left;width: '+t.width+'px; left: '+t.x+'px; top: '+yy+'px;z-index:'+zIndex+';" class="toso_dialogue"><div class="toso_content toso_bg_'+bg_color[t.back]+' toso_font_'+font_color[t.color]+'" title="'+title+'">'+t.content+'</div></div>');
			}else{
				html='<div id="tucao_'+t.tucao_id+'" style="'+opacity+'display:none;float:left;width: '+t.width+'px; left: '+t.x+'px; top: '+yy+'px;z-index:'+zIndex+';" class="toso_dialogue">';
				html+='<div class="toso_title handler" style="display:none;"><a href="###" class="close"></a></div>';
				html+='<div class="toso_content toso_font_'+font_color[t.color]+' toso_bg_'+bg_color[t.back]+'" title="'+title+'"><p>'+t.content+'</p>';
				html+='</div>';
				html+='</div>';
				el=$(html);
			}
			
			el.click(function(){$(this).css('z-Index',zIndex++);});
			panel.append(el);
			el.fadeIn();
			if(right){
				//拖拽修改宽度事件
				el.resizable({
					containment: 'parent',
					handles: 'w, e ,se',
					autoHide:true,
					maxWidth:max_w,
					minWidth:min_w,
					maxHeight:400,
					start:function(){
						stop();
					},
					resize:function(event, ui) {
						$(this).css('height','auto');
						$(this).find('.toso_content').css('height','auto');
					},
					stop:function(event,ui){
						$(this).find('.toso_content').css('height','1%');
						resize_tucao(t.tucao_id,$(this).width(),$(this).height());
						if(old_play) play();
					}
				});			
				//拖拽修改位置事件
				el.draggable({ 
					handle:'div.toso_title',
					containment: 'parent',
					opacity: opts.opacity*0.8,
					start:function(){
						stop();
					},
					stop: function(event, ui) {
						var pos=$(this).position();
						move_tucao(t.tucao_id,pos.left,pos.top+top_offest);
						if(old_play) play();
					}
				});
				if(t.back==3){
					el.hover(function(){
						$(this).find('div.handler').show();
						$(this).find('div.toso_content').addClass('toso_bg_no_hover');
					},function(){
						$(this).find('div.handler').hide();
						$(this).find('div.toso_content').removeClass('toso_bg_no_hover');
					});	
				}else{
					el.hover(function(){
						$(this).find('div.handler').show();
					},function(){
						$(this).find('div.handler').hide();
					});
				}
				//关闭事件
				el.find('.close').click(function(){
					if(confirm('确认要删除吗？')){
						delete_tucao(t.tucao_id);
					}
				});
			}
		}
		function remove_tucao(t){
			$('#tucao_'+t.tucao_id).remove();
		}
		function remove_all_tucao(){
			$('.toso_dialogue').remove();
		}
		
		function move_tucao(tucao_id,x,y){
			$.ajax({
				url:'/www/ajax.php?mod=tucao&act=move_tucao',
				data:{x:x,y:y,tucao_id:tucao_id},
				dataType:'json',
				cache:false,
				success:function(o){if(o.code<=0){showMsg(o.message);}}
			});
		}
		
		function resize_tucao(tucao_id,w,h){
			$.ajax({
				url:'/www/ajax.php?mod=tucao&act=resize_tucao',
				data:{w:w,h:h,tucao_id:tucao_id},
				dataType:'json',
				cache:false,
				success:function(o){if(o.code<=0){showMsg(o.message);}}
			});
		}
		
		function delete_tucao(tucao_id){
			$.ajax({
				url:'/www/ajax.php?mod=tucao&act=delete_tucao',
				data:{tucao_id:tucao_id},
				dataType:'json',
				cache:false,
				success:function(o){
					if(o.code>0){
						$('#tucao_'+tucao_id).remove();
					}else{
						showMsg(o.message);
					}
				}
			});
		}
		
		function get_list(size,type){
			if(list.length>0){
				first_id=list[0].tucao_id;
				last_id=list[list.length-1].tucao_id;
			}else{
				first_id=last_id=100000000;
			}
			$.ajax({
				url:'/www/ajax.php?mod=tucao&act=get_tucao',
				data:{first_id:first_id,last_id:last_id,type:type,page_size:size,object_id:object_id,object_type:object_type},
				dataType:'json',
				cache:false,error:function(){showMsg('通信错误，请稍后再试');is_loading=false;stop();},
				success:function(o){
					if(o.code<=0){showMsg(o.message);is_loading=false;return;}
					if(type=='next_page'){
						if(o.list.length==0 && list.length>0 && last_t!=null && list[list.length-1].tucao_id==last_t.tucao_id){
							showMsg('最后一页了,XD');
						}else{
							list=array_add_end(list,o.list);
							remove_all_tucao();
							last_i=-1;
							if(last_t==null){
								
							}else{
								for(i=0;i<list.length;i++){
									if(last_t.tucao_id==list[i].tucao_id){
										last_i=i;
									}
								}
							}
							if(last_i>=-1){
								for(i=last_i+1;i<list.length && i<last_i+1+page_size;i++){
									if(i==last_i+1)
										first_t=list[i];
									show_tucao(list[i]);
									last_t=list[i];
								}
							}
						}
						is_loading=false;
					}else if(type=='prev_page'){
						if(last_t==null || first_t==null ){
							showMsg('已经是第一页了,XD');
						}else if(o.list.length==0 && list.length>0 && first_t!=null && list[0].tucao_id==first_t.tucao_id){
							showMsg('已经是第一页了,XD');//alert(list[0].tucao_id+' '+first_t.tucao_id);
						}else{
							list=array_add_start(list,o.list);
							remove_all_tucao();
							first_i=-1;
							if(first_t==null){
								first_i=list.length;
							}else{
								for(i=list.length-1;i>=0;i--){
									if(first_t.tucao_id==list[i].tucao_id){
										first_i=i;break;
									}
								}
							}
							if(first_i>0){
								for(i=first_i-1;i>=0 && i>first_i-1-page_size;i--){
									if(i==first_i-1)
										last_t=list[i];
									show_tucao(list[i]);
									first_t=list[i];
								}
							}
						}
						is_loading=false;
					}else if(type=='next'){
						if(o.list.length==0){
							stop();
						}else{
							list=array_add_end(list,o.list);
							count=$('.toso_dialogue').length;
							//alert('a');
							if(first_t==null || last_t==null){
								show_tucao(list[0]);
								first_t=list[0];
								last_t=list[0];
								//alert('b');
							}else{
								//alert('c '+list.length);
								for(i=0;i<list.length;i++){
									if(count>=page_size && first_t.tucao_id==list[i].tucao_id){
										remove_tucao(list[i]);
										first_t=list[i+1];
										//alert('d');
										break;
									}
								}
								for(i=0;i<list.length;i++){
									if(last_t.tucao_id==list[i].tucao_id){
										show_tucao(list[i+1]);
										last_t=list[i+1];
										//alert('e');
										break;
									}	
								}
							}
						}
						is_loading=false;
					}
				}
			});
			
		}
		function array_add_start(arr1,arr2){
			var delete_count=arr1.length+arr2.length-opts.buffer*page_size;
			var re=[];
			for(i=0;i<arr2.length;i++){
				re.push(arr2[i]);
			}		
			if(delete_count>0){
				for(i=0;i<arr1.length;i++){
					if(i<arr1.length-delete_count){
						re.push(arr1[i]);
					}
				}
			}else{
				for(i=0;i<arr1.length;i++)
					re.push(arr1[i]);
			}
			return re;	
		}
		function array_add_end(arr1,arr2){
			var delete_count=arr1.length+arr2.length-opts.buffer*page_size;
			
			var re=[];
			if(delete_count>0){
				for(i=0;i<arr1.length;i++){
					if(i>=delete_count){
						re.push(arr1[i]);
					}
				}
			}else{
				for(i=0;i<arr1.length;i++){
						re.push(arr1[i]);
				}		
			}
			for(i=0;i<arr2.length;i++){
				re.push(arr2[i]);
				
			}
			return re;
		}
		
		//插入html到页面
		panel.after(bar);
	});
	
}

function mouseCoords(ev){
  if(ev.pageX || ev.pageY){
    return{x:ev.pageX, y:ev.pageY};
  }
  return{
    x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
    y:ev.clientY + document.body.scrollTop - document.body.clientTop
  };
} 



	



