function callback(fun,argum){
	fun(argum);
}

// 删除类型框
function delTypeBox(){
	$('input[name="publish_type"]').val( 0 );
	$('.talkPop').remove();
}

$(document).ready(function(){
	  // 评论切换
	  $("a[rel='comment']").live('click',function(){
	      var id = $(this).attr('minid');
	      var $comment_list = $("#comment_list_"+id);
		  if( $comment_list.html() == '' ){
			  $comment_list.html('<div class="feed_quote feed_wb" style="text-align:center"><img src="'+ _THEME_+'/images/icon_waiting.gif" width="15"></div>');
			$.post( U("weibo/Index/loadcomment"),{id:id},function(txt){
				$comment_list.html( txt ) ;
			});
		  }else{
			  $comment_list.html('');
		  }
	  });


	// 发布评论
	$("form[rel='miniblog_comment']").live("submit", function(){
		var _this = $(this);
		var callbackfun = _this.attr('callback');
		var _comment_content = _this.find("textarea[name='comment_content']");
		if( _comment_content.val()=='' ){
			ui.error('内容不能为空');
			return false;
		}
		_this.find("input[type='submit']").val( '评论中...').attr('disabled','true') ;
		var options = {
		    success: function(txt) {
				txt = eval('('+txt+')');
				_this.find("input[type='submit']").val( '确定');
			       _this.find("input[type='submit']").removeAttr('disabled') ;
				   _comment_content.val('');
				if(callbackfun){
					callback(eval(callbackfun),txt);
				}else{
					_comment_content.css('height','');
			       $("#comment_list_before_"+txt.data['weibo_id']).after( txt.html );

				   $("#replyid_" + txt.data['weibo_id'] ).val('');
				   //更新评论数
				   $("a[rel='comment'][minid='"+txt.data['weibo_id']+"']").html("评论("+txt.data['comment']+")");
				 //  _this.find("textarea[name='comment_content']").focus();
				   
				}
		    }
		};
		_this.ajaxSubmit( options );
	    return false;
	});
});

weibo = function(){
	
}

weibo.prototype = {
	//初始化微博发布
	init:function(option){
		var __THEME__ = "http://t.hkesp.com/public/themes/classic2";
		var Interval;
		$("#publish_type_content_before").html("<span>添加：</span><a href=\"javascript:void(0)\" target_set=\"content_publish\" onclick=\"ui.emotions(this)\" class=\"a52\"><img class=\"icon_add_face_d\" src=\""+__THEME__+"/images/zw_img.gif\" />表情</a> <a href=\"javascript:void(0)\" onclick=\"addtheme()\" class=\"a52\"><img class=\"icon_add_topic_d\" src=\""+__THEME__+"/images/zw_img.gif\" />话题</a> <a href=\"javascript:void(0)\" onclick=\"weibo.plugin.image.click(169)\" class=\"a52\"><img class=\"icon_add_img_d\" src=\""+__THEME__+"/images/zw_img.gif\" />图片</a> <a href=\"javascript:void(0)\" onclick=\"weibo.plugin.video.click(221)\" class=\"a52\"><img class=\"icon_add_video_d\" src=\""+__THEME__+"/images/zw_img.gif\" />视频</a> <a href=\"javascript:void(0)\" onclick=\"weibo.plugin.music.click(271)\" class=\"a52\"><img class=\"icon_add_music_d\" src=\""+__THEME__+"/images/zw_img.gif\" />音乐</a>");

		$("#content_publish").keypress(function(event){
			var key = event.keyCode?event.keyCode:event.which?event.which:event.charCode;
	        if (key == 27) {
	        	clearInterval(Interval);
	        }
			weibo.checkInputLength(this,140);
		}).blur(function(){
			clearInterval(Interval);
			weibo.checkInputLength(this,140);
		}).focus(function(){
			//微博字数监控
			clearInterval(Interval);
		    Interval = setInterval(function(){
		    	weibo.checkInputLength('#content_publish',140);
			},300);
		});
		weibo.checkInputLength('#content_publish',140);
		shortcut('ctrl+return',	function(){weibo.do_publish();clearInterval(Interval);},{'target':'miniblog_publish'});
	},
	//发布前的检测
	before_publish:function(){
		
		if( $.trim( $('#content_publish').val() ) == '' ){
            ui.error('内容不能为空');		
			return false;
		}
		return true;
	},
	//发布操作
	do_publish:function(){
		if( weibo.before_publish() ){
			weibo.textareaStatus('sending');
			var options = {
			    success: function(txt) {
			      if(txt){
			    	   weibo.after_publish(txt);
			      }else{
	                  alert( '发布失败' );
			      }
				}
			};		
			$('#miniblog_publish').ajaxSubmit( options );
		    return false;
		}
	},
	//发布后的处理
	after_publish:function(txt){
		if(txt==0) {
			ui.success('您发布的微博含有敏感词，请等待审核！');
		}else {
			delTypeBox();
		    $("#feed_list").prepend( txt ).slideDown('slow');
		    var sina_sync = $('#sina_sync').attr('checked');
		    $('#miniblog_publish').clearForm();
		    if (sina_sync) {
		    	$('#sina_sync').attr('checked', true);
		    }
		    weibo.upCount('weibo');
		    ui.success('微博发布成功');
		    weibo.checkInputLength('#content_publish',140);
		}
	},
	//发布按钮状态
	textareaStatus:function(type){
		var obj = $('#publish_handle');
		if(type=='on'){
			obj.removeAttr('disabled').attr('class','btn_big hand');
		//}else if( type=='sending'){
		//	obj.attr('disabled','true').attr('class','btn_big_disable hand');
		}else{
			obj.attr('disabled','true').attr('class','btn_big_disable hand');
		}
	},
	//删除一条微博
	deleted:function(weibo_id){
		$.post(U("weibo/Operate/delete"),{id:weibo_id},function(txt){
			if( txt ){
				$("#list_li_"+weibo_id).slideUp('fast');
				weibo.downCount('weibo');
			}else{
				alert('删除失败');
			}
		});
	},
	//收藏
	favorite:function(id,o){
		$.post( U("weibo/Operate/stow") ,{id:id},function(txt){
			if( txt ){
				$(o).wrap('<span id=content_'+id+'></span>');
				$('#content_'+id).html('已收藏');
			}else{
				alert('收藏失败');
			}
		});
	},
	//取消收藏
	unFavorite:function(id,o){
		$.post( U("weibo/Operate/unstow") ,{id:id},function(txt){
			if( txt ){
				$('#list_li_'+id).slideUp('slow');
			}else{
				alert('取消失败');
			}
		});
	},
	//转发
	transpond:function(id,upcontent){
		upcontent = ( upcontent == undefined ) ? 1 : 0;
		ui.box.load( U("weibo/operate/transpond",["id="+id,"upcontent="+upcontent] ),{title:'转发',closeable:true});
	},
	//关注话题
	followTopic:function(name){
		$.post(U('weibo/operate/followtopic'),{name:name},function(txt){
			txt = eval( '(' + txt + ')' );
			if(txt.code==12){
				$('#followTopic').html('<a href="javascript:void(0)" onclick="weibo.unfollowTopic(\''+txt.topicId+'\',\''+name+'\')">取消该话题</a>');
			}
		});
	},
	unfollowTopic:function(id,name){
		$.post(U('weibo/operate/unfollowtopic'),{topicId:id},function(txt){
			if(txt=='01'){
				$('#followTopic').html('<a href="javascript:void(0)" onclick="weibo.followTopic(\''+name+'\')">关注该话题</a>');
			}
		});	
	},
	quickpublish:function(text){
		$.post(U('weibo/operate/quickpublish'),{text:text},function(txt){
			ui.box.show(txt,{title:'说几句',closeable:true});
		});
	},
	//更新计数器
	upCount:function(type){
		if(type=='weibo'){
			$("#miniblog_count").html( parseInt($('#miniblog_count').html())+1 );
		}
	},
	downCount:function(type){
		if(type=='weibo'){
			$("#miniblog_count").html( parseInt($('#miniblog_count').html())-1 );
		}
	},
	//检查字数输入
	checkInputLength:function(obj,num){
		var len = getLength($(obj).val(), true);
		var wordNumObj = $('.wordNum');
		
		if(len==0){
			wordNumObj.css('color','').html('你还可以输入<strong id="strconunt">'+ (num-len) + '</strong>字');
			weibo.textareaStatus('off');
		}else if( len > num ){
			wordNumObj.css('color','red').html('已超出<strong id="strconunt">'+ (len-num) +'</strong>字');
			weibo.textareaStatus('off');
		}else if( len <= num ){
			wordNumObj.css('color','').html('你还可以输入<strong id="strconunt">'+ (num-len) + '</strong>字');
			weibo.textareaStatus('on');
		}
	},
	publish_type_box:function(type_num,content,mg_left){
		var __THEME__ = "http://t.hkesp.com/public/themes/classic2";
		var html = '<div class="talkPop"><div  style="position: relative; height: 7px; line-height: 3px;">'
		     + '<img class="talkPop_arrow" style="margin-left:'+ mg_left +'px;position:absolute;" src="'+__THEME__+'/images/zw_img.gif" /></div>'
             + '<div class="talkPop_box">'
			 + '<div class="close" id="weibo_close_handle"><a href="javascript:void(0)" class="del" onclick=" delTypeBox()" > </a></div>'
			 + '<div id="publish_type_content">'+content+'</div>'
			 + '</div></div>';
		$('input[name="publish_type"]').val( type_num );
		$('div.talkPop').remove();
		$("#publish_type_content_before").after( html );
	}
}


weibo = new weibo();

weibo.plugin = {};

function addtheme(){
	var text = '#请在这里输入自定义话题#';
	var   patt   =   new   RegExp(text,"g");  
	var content_publish = $('#content_publish');
	var result;
				
	if( content_publish.val().search(patt) == '-1' ){
		content_publish.val( content_publish.val() + text);
	}
	
	var textArea = document.getElementById('content_publish');
	
	result = patt.exec( content_publish.val() );
	
	var end = patt.lastIndex-1 ;
	var start = patt.lastIndex - text.length +1;
	
	if (document.selection) { //IE
		 var rng = textArea.createTextRange();
		 rng.collapse(true);
		 rng.moveEnd("character",end)
		 rng.moveStart("character",start)
		 rng.select();
	}else if (textArea.selectionStart || (textArea.selectionStart == '0')) { // Mozilla/Netscape…
        textArea.selectionStart = start;
        textArea.selectionEnd = end;
    }
    textArea.focus();
	weibo.checkInputLength('#content_publish',140);
	return ;
}jQuery.extend(weibo.plugin, {	video:function(element, options){	   	    	}});jQuery.extend(weibo.plugin.video, {	html:'<div id="video_input">请输入新浪播客、优酷网、土豆网、酷6网、搜狐视频等视频网站的视频播放页链接： <div><input name="publish_type_data" type="text" style="width: 235px" class="text mr5" value="" /><input type="button" class="btn_b" onclick="weibo.plugin.video.add_video()" value="添加"></div></div><div style="display:none"    id="video_add_complete">添加完成</div>',	click:function(options){	   weibo.publish_type_box(3,this.html,options)	},	add_video:function(){		var video_url = $("input[name='publish_type_data']").val();		$.post( U('weibo/plugins/before_publish'),{url:video_url,plugin_id:3},function(txt){			txt = eval('('+txt+')');			if(txt.boolen){				$('#video_input').hide();				$('#video_add_complete').show();				$("#content_publish").val( $("#content_publish").val( ) + ' ' + txt.data + ' ');				weibo.checkInputLength('#content_publish',140);				$('div .talkPop').hide();			}else{				alert(txt.message);			}		})	}});function switchVideo(id,type,host,flashvar){	if( type == 'close' ){		$("#video_mini_show_"+id).show();		$("#video_content_"+id).html( '' );		$("#video_show_"+id).hide();	}else{		$("#video_mini_show_"+id).hide();		$("#video_content_"+id).html( showFlash(host,flashvar) );		$("#video_show_"+id).show();			}}//显示视频function showFlash( host, flashvar) {	var flashAddr = {		'youku.com' : 'http://player.youku.com/player.php/sid/FLASHVAR/v.swf',		'ku6.com' : 'http://player.ku6.com/refer/FLASHVAR/v.swf',		//'sina.com.cn' : 'http://vhead.blog.sina.com.cn/player/outer_player.swf?vid=FLASHVAR',		'sina.com.cn' : 'http://you.video.sina.com.cn/api/sinawebApi/outplayrefer.php/vid=FLASHVAR/s.swf',		//'tudou.com' : 'http://www.tudou.com/v/FLASHVAR',		'tudou.com' : 'http://www.tudou.com/v/FLASHVAR/&autoPlay=true/v.swf',		'youtube.com' : 'http://www.youtube.com/v/FLASHVAR',		'5show.com' : 'http://www.5show.com/swf/5show_player.swf?flv_id=FLASHVAR',		//'sohu.com' : 'http://v.blog.sohu.com/fo/v4/FLASHVAR',		'sohu.com' : 'http://share.vrs.sohu.com/FLASHVAR/v.swf',		'mofile.com' : 'http://tv.mofile.com/cn/xplayer.swf?v=FLASHVAR',		'music' : 'FLASHVAR',		'flash' : 'FLASHVAR'	};	var videoFlash = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="430" height="400">'        + '<param value="transparent" name="wmode"/>'		+ '<param value="FLASHADDR" name="movie" />'		+ '<embed src="FLASHADDR" wmode="transparent" allowfullscreen="true" type="application/x-shockwave-flash" width="430" height="400"></embed>'		+ '</object>';	var flashHtml = videoFlash;	flashvar = encodeURI(flashvar);	if(flashAddr[host]) {		var flash = flashAddr[host].replace('FLASHVAR', flashvar);		flashHtml = flashHtml.replace(/FLASHADDR/g, flash);	}	return flashHtml;}jQuery.extend(weibo.plugin, {	music:function(element, options){	   	    	}});jQuery.extend(weibo.plugin.music, {	html:'<div id="music_input">请输入歌曲链接地址：<div><input name="publish_type_data" type="text" style="width: 235px"   class="text  mr5"  value="" /><input type="button" class="btn_b" onclick="weibo.plugin.music.add_music()" value="添加"></div></div><div style="display:none" id="music_add_complete">添加完成</div>',	click:function(options){	   weibo.publish_type_box(4,this.html,options)	},	add_music:function(){		var video_url = $("input[name='publish_type_data']").val();		var point = video_url.lastIndexOf(".");		var type = video_url.substr(point);		if( type.toLowerCase() != '.mp3'){			alert('只能发布以mp3结尾的音乐');			return false;		}		$.post( U('weibo/plugins/before_publish'),{url:video_url,plugin_id:4},function(txt){			txt = eval('('+txt+')');			if(txt.boolen){				$('#music_input').hide();				$('#music_add_complete').show();				$("#content_publish").val( $("#content_publish").val( ) + ' ' + txt.data + ' ');				weibo.checkInputLength('#content_publish',140);				$('div .talkPop').hide();			}else{				alert(txt.message);			}		})	}});jQuery.extend(weibo.plugin, {
	image:function(element, options){
	   
	    
	}
});

var stopUploadPic = 0;
jQuery.extend(weibo.plugin.image, {
	html:'<div id="upload_selectpic"><div class="btn_green" href="javascript:void(0);" >从电脑选择图片'+
	'<form action="'+U("weibo/plugins/before_publish")+'" enctype="multipart/form-data" method="post" id="uploadpic">'+
	'<input type="hidden" name="plugin_id" value="1"><input type="file" hidefoucs="true" name="pic" onchange="weibo.plugin.image.upload(this)">'+
	'</form></div><div>仅支持JPG、GIF、PNG、JPEG图片文件，且文件小于2M</div></div><div class="alC pt10 pb10 f14px" id="upload_loading" style="display:none"><img src="'+ _THEME_+'/images/icon_waiting.gif" width="20" class="alM"> 正在上传中...<br /><a class="btn_w mt10" href="javascript:void(0)" onclick="$(\'div .talkPop\').remove();weibo.plugin.image.stopAjax();">取消上传</a></div>',
	click:function(options){
		if (1 != $('div.talkPop').data('type')) {
			weibo.publish_type_box(1,this.html,options);
		}
	},
	upload:function(o){
		var allowext = ['jpg','jpeg','gif','png'];
		var ext = /\.[^\.]+$/.exec( $(o).val() );
		ext = ext.toString().replace('.','');
		if( jQuery.inArray( ext.toLowerCase() , allowext )==-1 ){
			alert('只允许上传jpg、jpeg、gif、png格式的图片');
			return false;
		}
		weibo.textareaStatus('off');
		$('#upload_selectpic').hide();
		$('#upload_loading').show();
		$('#weibo_close_handle').hide();
		var options = {
			    success: function(txt) {
				if(stopUploadPic==1){
					return false;
				}
			      txt = eval( '(' + txt + ')' );
			      if(txt.boolen==1){
						var img = new Image;
						img.src = txt.picurl;
						img.onload = function(){
							if( this.width>100 || this.height>100 ){
								var style;
								if( this.height >  this.width ){
									style = "height:100px;width:"+this.width*(100/this.height)+"px";
								}else{
									style = "width:100px;height:"+this.height*(100/this.width)+"px";
								}
								
								var html = "<img src='"+txt.picurl+"' style='"+style+"'><input name='publish_type_data' type='hidden' style='width:86%' value="+txt.type_data+" />";
							}else{
								var html = "<img src='"+txt.picurl+"'><input name='publish_type_data' type='hidden' style='width:86%' value="+txt.type_data+" />";					}
							if($('#content_publish').val()==''){
								$('#content_publish').val('图片分享 ');
							}
							$("#publish_type_content").html( txt.file_name+'&nbsp;&nbsp;&nbsp;<a href="javascript:void(0)" onclick="$(\'div .talkPop\').remove();">删除图片</a><BR>'+html );
							$('div.talkPop').data('type', 1);
							$('#upload_loading').hide();
							$('#upload_selectpic').show();
							weibo.checkInputLength('#content_publish',140);
						};
								
				  }else{
					alert( txt.message );
					$('.talkPop').remove();
			      }
			    } 
			};
//			$('#publish_type_content').html('<div style="width:400px;text-align:center;height:150px;"><img src="__THEME__/images/icon_waiting.gif" width="30"></div>');
			var httpRespondHandle = $('#uploadpic').ajaxSubmit( options );
		    return false;
	},
	stopAjax:function(){
		stopUploadPic=1;
	}

});

//切换图片
function switchPic(id,type,picurl){
	if( type=='close' ){
		$("#pic_show_"+id).hide();
		$("#pic_mini_show_"+id).show();
	}else{
		
		if( $("#pic_show_"+id).find('.imgSmall').attr('src')==''){
			$("#pic_mini_show_"+id).find('.loadimg').show();
			var img = new Image;
			img.src = picurl+'?time='+new Date();
			img.onload = function(){
				if( this.width>460 ){
					$("#pic_show_"+id).find('.imgSmall').css('width','460px');
				}
				$("#pic_show_"+id).find('.imgSmall').attr('src',this.src);
				$("#pic_mini_show_"+id).find('.loadimg').hide();
				$("#pic_show_"+id).show();
				$("#pic_mini_show_"+id).hide();	
			};
		}else{
			$("#pic_show_"+id).show();
			$("#pic_mini_show_"+id).hide();	
		}
	}
}

//旋转图片
function revolving(id,type){
	var img = $("#pic_show_"+id).find('.imgSmall');
	img.rotate(type);
}


$.fn.rotate = function(p){

	var img = $(this)[0],
		n = img.getAttribute('step');
	// 保存图片大小数据
	if (!this.data('width') && !$(this).data('height')) {
		this.data('width', img.width);
		this.data('height', img.height);
	};
	this.data('maxWidth',img.getAttribute('maxWidth'))

	if(n == null) n = 0;
	if(p == 'left'){
		(n == 0)? n = 3 : n--;
	}else if(p == 'right'){
		(n == 3) ? n = 0 : n++;
	};
	img.setAttribute('step', n);

	// IE浏览器使用滤镜旋转
	if(document.all) {
		if(this.data('height')>this.data('maxWidth') && (n==1 || n==3) ){
			if(!this.data('zoomheight')){
				this.data('zoomwidth',this.data('maxWidth'));
				this.data('zoomheight',(this.data('maxWidth')/this.data('height'))*this.data('width'));
			}
			img.height = this.data('zoomwidth');
			img.width  = this.data('zoomheight');
			
		}else{
			img.height = this.data('height');
			img.width  = this.data('width');
		}
		
		img.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation='+ n +')';
		// IE8高度设置
		if ($.browser.version == 8) {
			switch(n){
				case 0:
					this.parent().height('');
					//this.height(this.data('height'));
					break;
				case 1:
					this.parent().height(this.data('width') + 10);
					//this.height(this.data('width'));
					break;
				case 2:
					this.parent().height('');
					//this.height(this.data('height'));
					break;
				case 3:
					this.parent().height(this.data('width') + 10);
					//this.height(this.data('width'));
					break;
			};
		};
	// 对现代浏览器写入HTML5的元素进行旋转： canvas
	}else{
		var c = this.next('canvas')[0];
		if(this.next('canvas').length == 0){
			this.css({'visibility': 'hidden', 'position': 'absolute'});
			c = document.createElement('canvas');
			c.setAttribute('class', 'maxImg canvas');
			img.parentNode.appendChild(c);
		}
		var canvasContext = c.getContext('2d');
		switch(n) {
			default :
			case 0 :
				img.setAttribute('height',this.data('height'));
				img.setAttribute('width',this.data('width'));
				c.setAttribute('width', img.width);
				c.setAttribute('height', img.height);
				canvasContext.rotate(0 * Math.PI / 180);
				canvasContext.drawImage(img, 0, 0);
				break;
			case 1 :
				if(img.height>this.data('maxWidth') ){
					h = this.data('maxWidth');
					w = (this.data('maxWidth')/img.height)*img.width;
				}else{
					h = this.data('height');
					w = this.data('width');
				}
				c.setAttribute('width', h);
				c.setAttribute('height', w);
				canvasContext.rotate(90 * Math.PI / 180);
				canvasContext.drawImage(img, 0, -h, w ,h );
				break;
			case 2 :
				img.setAttribute('height',this.data('height'));
				img.setAttribute('width',this.data('width'));
				c.setAttribute('width', img.width);
				c.setAttribute('height', img.height);
				canvasContext.rotate(180 * Math.PI / 180);
				canvasContext.drawImage(img, -img.width, -img.height);
				break;
			case 3 :
				if(img.height>this.data('maxWidth') ){
					h = this.data('maxWidth');
					w = (this.data('maxWidth')/img.height)*img.width;
				}else{
					h = this.data('height');
					w = this.data('width');
				}
				c.setAttribute('width', h);
				c.setAttribute('height', w);
				canvasContext.rotate(270 * Math.PI / 180);
				canvasContext.drawImage(img, -w, 0,w,h);
				break;
		};
	};
};