var cite =Class.create();
Object.extend(cite,{
	flag : false,
	tmp_url : '',
	shareFlag : null,
	cur_vote : null,
	newUri : null,
	share_title : null,
	appUri : {
		qq : 'http://v.t.qq.com/share/share.php',
		sina : 'http://service.weibo.com/share/share.php'
	},
	// 提示模板
	loading_tmp : '<div id="loading" style="width: 240px;" class="popup">\
		<div class="panel_wrap">\
			<div class="popup-top">\
				<div class="popup-top-right">\
					<div class="popup-top-mid"></div>\
				</div>\
			</div>\
			<div class="popup-mid">\
				<div class="popup-mid-main">\
					<div class="popup-mid-main-mid">\
						<div class="popup-mid-main-mid-content"><span class="loading_icon"></span>#{msg}</div>\
					</div>\
				</div>\
			</div>\
			<div class="popup-bottom">\
				<div class="popup-bottom-right">\
					<div class="popup-bottom-mid"></div>\
				</div>\
			</div>\
		</div>\
	</div>',
	// 显示抓取浮动提示框
	show_loading : function(id,msg){
		var t = new Template(cite.loading_tmp);
		var obj = $(id);
		var dem = obj.getDimensions();
		var offset = obj.cumulativeOffset();
		$(document.body).insert(t.evaluate({msg:msg}));
		$('loading').absolutize();
		$('loading').setStyle({
			top: (offset.top + dem.height + 3) + "px",
			left: (offset.left) + "px",
			zIndex : 20
		})
	},
	
	// 检查url
	check_url : function (urlObj){
		var id = urlObj.id;
		var url = urlObj.value;
		if(this.tmp_url == url){
			return false;
		}
		this.tmp_url = url;
		if(!url) {
			$('cite_form').reset();
			$('res_id').value = '';
			$('resourse').value = '';
			$('from').value = '';
			$('from_uid').value = '';
			$('author').value = '';
			$('type').value = '';
			$('preview_img').value ='';
			$('discription').value = '';
			$('contents').value = '';
			content_editor.setContent('');
			return false;
		}
		if(url.search(/178.com|youku.com|tudou.com|ngacn.cc|nicovideo.jp|sc2.cc/i) == -1){
//			ErrorTips.add('url', 'warning', '本站暂时还无法提供来自此站点的自动转帖，请手动填写！');
//			$('errorTip').innerHTML = '<span class="fixie6png tip-icon friendly-tip-icon"></span>本站暂时还无法提供来自此站点的自动转帖，请手动填写！';
			return false;
		}
		if(url.search(/album.category.photo_list|cite.index.viewAlbum|cite.index.viewPhoto/) >0 ){
			return false;
		}
		this.show_loading(urlObj.id,'信息采集中，请稍后...');
		new Ajax.Request("/~cite.index.checkResource",{
				method: 'post',
				parameters: $H({url: url}).toQueryString(),
				onComplete: function(transport){
					$('loading').remove();
					var ret = (transport.responseText).evalJSON();
					
					if(ret.status == 'success'){
						if(ret.resourse){
							$('resourse').value = ret.resourse;
						}
						if(ret.title && !$('title').value){
							$('title').value = ret.title;
						}
						if(ret.res_id){
							$('res_id').value = ret.res_id;
						}
						if(ret.from){
							$('from').value = ret.from;
						}
						if(ret.from_uid){
							$('from_uid').value = ret.from_uid;
						}
						if(ret.author){
							$('author').value = ret.author;
						}
						if(ret.type){
							$('type').value = ret.type;
						}
						if(ret.preview_img){
							$('preview_img').value = ret.preview_img;
						}
						if(ret.discription){
							$('discription').value = ret.discription;
						}
						if(ret.url){
							$('url').value = ret.url;
						}
						$('out').value = ret.out;
//						ErrorTips.add('url', 'friendly',ret.msg,{width:'270px'});
						$('contents').value = ret.contents;
						content_editor.setContent(ret.contents);
					}else{
						$('url').value = url;
						new MessageBox(MessageBox.TYPE_MESSAGE, ret.msg, '错误', {});
						return false;
//						if(!$('mbox_error_1')){
//							ErrorTips.add('url', 'warning', ret.msg,{width:'100px'});
//							Tips.add("title", '<span class="fixie6png tip-icon friendly-tip-icon"></span>' + res.msg,['blur'],['focus']);
//							$('errorTip').innerHTML = '<span class="fixie6png tip-icon friendly-tip-icon"></span>' + res.msg;
//						}else{
//							ErrorTips.add('url', 'warning', ret.msg,{width:'270px'});
//							Tips.add("title", '<span class="fixie6png tip-icon friendly-tip-icon"></span>' + res.msg,['blur'],['focus']);
//							$('errorTip').innerHTML = '<span class="fixie6png tip-icon friendly-tip-icon"></span>' + res.msg;
//						}
					}
					return false;
				}
		});
		return false;
	},
	shareUrl : function (type){
		if(type != null){
			var shareType = type;
			var uri = cite.newUri == null ? encodeURIComponent(self.location.href) : 'http://i.178.com' + cite.newUri;
//			var pic = $('pic').innerHTML;
//			var pic = 'http://g2.ykimg.com/0100641F464E33C109420F01FE47027E98C6AE-5C20-8976-CEA8-32A5C0210F22';
//			var uri = encodeURIComponent('http://i.178.com/~cite.index.viewcite/id/3856209/uid/1334701');
			var shareUri = cite.appUri[type];
			var vote = cite.cur_vote;
//			var vote = '了开始的减肥上来看法';
			shareUri += "?url=" + uri;
			shareUri += "&appkey=";
//			shareUri += "&pic=" + encodeURIComponent(pic);
			shareUri += "&title=" + encodeURIComponent('#178转帖# 我对《' + (cite.share_title == null ? $('title').innerHTML : cite.share_title) + '》发表了观点：“' + vote + '”');
			return shareUri
//			window.open(shareUri,"_blank","width=615,height=505");
		}
	},
	share :function(){
		var qqUri = cite.shareUrl('qq');
		var sinaUri = cite.shareUrl('sina');
		var msg = '<div class="interactive-opinion-weibo">\
			<p>转帖成功，是否分享到微博：</p>\
			<br/>\
			<a href="' + qqUri + '" id="qq" onclick="cite.addweiboCount(\'qq\');" class="qq" target="_blank">腾讯微博</a>\
			<a href="' + sinaUri + '" id="sina" onclick="cite.addweiboCount(\'sina\');" class="sina" target="_blank">新浪微博</a>\
		</div>';
		new MessageBox(MessageBox.TYPE_MESSAGE, msg, '分享微博', {close: function(){ 
			if(cite.newUri == null){
				window.location.reload();
			}else{
				location.href=cite.newUri;
			}
		}});
	},
	addweiboCount : function(type){
		new Ajax.Request("/~cite.index.addWeiboCount",{
			method : 'post',
			parameters : 'type=' + type,
			onComplete : function(transport){
				var ret = transport.responseText;
				if(cite.newUri == null){
					window.location.reload();
				}else{
					location.href=cite.newUri;
				}
			}
		});
	},
	
	//显示弹窗
	show_panel : function(url){
		var title = $('title').innerHTML;
		new Ajax.Request("/~cite.index.panel",{
			method : 'post',
			onComplete : function(transport){
				var ret = transport.responseText;
				var tpl = '<form method="POST" id="cite_form" name="cite_form" action="/~cite.index.quickCite">\
							<textarea name="postcontent" id="comments" style="display:none;"></textarea>\
							<input type="hidden" name="citeType" id="citeType" value="1" />\
							<div class="part-title-class">\
								<ul class="part-title-nav">\
									<li id="all" class="selected"  onclick="$(\'friendsLists\').hide();$(\'citeType\').value=1;this.className=\'selected\';$(\'frd\').className=\'\';$(\'show_lang\').innerHTML=\'评价：\'">\
										<a href="javascript:;"><span>转帖给所有好友</span></a>\
									</li>\
									<li id="frd" onclick="$(\'friendsLists\').show();$(\'citeType\').value=2;this.className=\'selected\';$(\'all\').className=\'\';$(\'show_lang\').innerHTML=\'附言：\'">\
										<a href="javascript:;"><span>发送给好友</span></a>\
									</li>\
								</ul>\
							</div>\
							<ul class="write-repaste">\
								<li class="li-repaste"><span>原帖标题：</span><span style="width:248px;text-align:left;">'+title+'</span></li>\
								'+ret+'\
							</ul>\
						</form>';
				new MessageBox(MessageBox.TYPE_OK_CANCEL,tpl,'转帖',{
					ok : function(){
						var post_content = 'post_content_'+$('rand').value;
						eval('var contents ='+ post_content+'.getHtml();');
						var uri = self.location.href;
						var params = 'url=' + encodeURIComponent(uri);
						
						if(contents){params += '&comments=' + contents;}
						if($('list_id')){params += '&id=' + $('list_id').value;}
						if($('citeRes_id')){params += '&res_id=' + $('citeRes_id').value;}
						if($('citeType')){params += '&citeType=' + $('citeType').value;}
						if($('to_user')){params += '&to_user=' + encodeURIComponent($('to_user').value);}
						new Ajax.Request('/~cite.index.quickCite',{
							method : 'post',
							parameters : params,
							onComplete : function(transport){
								var ret = (transport.responseText).evalJSON();
								if(ret.status == 'success'){
//									alert(ret.msg);
									new MessageBox(MessageBox.TYPE_MESSAGE, ret.msg, '成功', {});
								}else{
//									alert(ret.msg);
									new MessageBox(MessageBox.TYPE_MESSAGE, ret.msg, '错误', {});
								}
							}
						});
						return false;
					},
					cancel:function(){return false;}
				},{'width':600});
			}
		});
	},
	//投票
	postVote : function (res_id,kid){
		if($('attend').value == 0){
//			alert('你已经吐槽过一次了~~');
			new MessageBox(MessageBox.TYPE_MESSAGE, '你已经吐槽过一次了~~', '错误', {});
			return false;
		}
		cite.cur_vote = $('pid_' + kid).innerHTML;
		var url ='/~cite.index.postVote';
		new Ajax.Request(url,{
			method : 'post',
			parameters : 'res_id=' + res_id + '&vote_key=' + kid,
			onComplete : function(transport){
				var ret = (transport.responseText).evalJSON();
				if(ret.status == 'success'){
					if(ret.ctn == 1) {
						var msg = ret.ctn == 1 ? ret.msg+'是否转帖' : ret.msg;
						new MessageBox(MessageBox.TYPE_OK_CANCEL,msg,'转帖',{
							ok : function(){
								new Ajax.Request('/~cite.index.quickCite',{
									method : 'post',
									parameters: 'id=' + $('list_id').value + '&res_id=' + res_id,
									onComplete : function(transport){
										var ret = (transport.responseText).evalJSON();
										if(ret.status == 'success'){
//											alert(ret.msg);
//											new MessageBox(MessageBox.TYPE_MESSAGE, ret.msg, '成功', {});
											
											cite.share();
										}else{
//											alert(ret.msg);
											new MessageBox(MessageBox.TYPE_MESSAGE, ret.msg, '错误', {});
											if(ret.login){
												window.open('http://i.178.com/');
											}
										}
									}
								});
							},
							cancel:function(){window.location.href = location.href;return false;}
						});
					}else{
//						alert(ret.msg);
						new MessageBox(MessageBox.TYPE_MESSAGE, ret.msg, '成功', {close: function(){ window.location.reload();}});
					}
				}else{
//					alert(ret.msg);
					new MessageBox(MessageBox.TYPE_MESSAGE, ret.msg, '错误', {});
					if(ret.login){
						window.open('http://i.178.com/');
					}
				}
			}
		});
		return false;
	},

	
	//添加互动观点
	addVote : function (form){
		$('errorTips').innerHTML = '';
		if(!$('vote_key').value){
//			$('errorTips').innerHTML = '<span class="fixie6png tip-icon warning-tip-icon"></span>请您输入相应的互动观点。'
			new MessageBox(MessageBox.TYPE_MESSAGE, '请您输入相应的互动观点', '错误', {});
			return false;
		}
		if($('vote_key').value == '说点儿啥呗~') {$('vote_key').value=''; new MessageBox(MessageBox.TYPE_MESSAGE, '互动观点不能为空', '错误', {});return false;}
		if(this.checkLen($('vote_key').value) > 20){
			$('errorTips').innerHTML = '<span class="fixie6png tip-icon warning-tip-icon"></span>你说的太多了~'
			return false;
		}
		var form = $(form);
		cite.cur_vote = $('vote_key').value;
		if($('advt')){$('advt').disabled = true;$('advt').hide();}
		form.request({
			onComplete : function (transport){
				var ret = (transport.responseText).evalJSON();
				if($('advt')){$('advt').disabled = false;}
				if(ret.status == 'success'){
					if(ret.ctn == 1) {
						var msg = ret.ctn == 1 ? ret.msg+'是否转帖' : ret.msg;
						new MessageBox(MessageBox.TYPE_OK_CANCEL,msg,'转帖',{
							ok : function(){
								new Ajax.Request('/~cite.index.quickCite',{
									method : 'post',
									parameters: 'id=' + $('list_id').value + '&res_id=' + $('citeRes_id').value + '&url=' + encodeURIComponent(location.href),
									onComplete : function(transport){
										var ret = (transport.responseText).evalJSON();
										if(ret.status == 'success'){
//											alert(ret.msg);
//											new MessageBox(MessageBox.TYPE_MESSAGE, ret.msg, '成功', {close: function(){ window.location.reload();}});
											cite.share();
										}else{
//											alert(ret.msg);
											new MessageBox(MessageBox.TYPE_MESSAGE, ret.msg, '错误', {});
										}
									}
								});
							},
							cancel:function(){window.location.href = location.href;}
						});
					}else{
						new MessageBox(MessageBox.TYPE_MESSAGE, ret.msg, '成功', {close: function(){ window.location.reload();}});
					}
				}else{
					new MessageBox(MessageBox.TYPE_MESSAGE, ret.msg, '错误', {});
				}
			}
		});
		return false;
	},
	//显示互动观点墙
	showVoteList : function (res_id){
		new Ajax.Request('/~cite.index.viewVoteList/res_id/' + res_id,{
			method : 'get',
			onComplete : function(transport){
				var ret = transport.responseText
				$('voteList').innerHTML = ret;
			}
		});
	},
	
	b_strlen : function (a){
		for(var b = 0,c = 0;c < a.length;c++)
			b=a.charCodeAt(c) < 0 || a.charCodeAt(c) > 255 ? b+2 : b+1;
		return b
	},
	
		
	substr : function (str,len){
		var tmp = '';
		for(var b = 0,c = 0;c < str.length;c++){
			var d =b;
			var ret = tmp;
			b=str.charCodeAt(c) < 0 || str.charCodeAt(c) > 255 ? b+2 : b+1;
			tmp += str.charAt(c);
			if(b > len){
				break;
			}
		}
		return ret;
	},
	
	//提交新建转帖
	checkCite : function (form){
		var form = $(form);
		$('contents').value = content_editor.getHtml();
		if($('url').value == '选填') {$('url').value='';}
		if(!$('title').value) {new MessageBox(MessageBox.TYPE_MESSAGE, '标题不能为空', '错误', {}); return false;}
		if($('title').value.length >200) {new MessageBox(MessageBox.TYPE_MESSAGE, '标题长度不能超过200个字', '错误', {}); return false;}
		if($('title').value.length <2) {new MessageBox(MessageBox.TYPE_MESSAGE, '标题长度不能少于2个字', '错误', {}); return false;}
		if($('contents').value.length < 5) {new MessageBox(MessageBox.TYPE_MESSAGE, '内容不能为少于5个字', '错误', {}); return false;}
		if($('vote_key').value == '说点儿啥呗~') {$('vote_key').value=''; new MessageBox(MessageBox.TYPE_MESSAGE, '互动观点不能为空', '错误', {});return false;}
		if(!$('vote_key').value) {new MessageBox(MessageBox.TYPE_MESSAGE, '互动观点不能为空', '错误', {});$('vote_key').focus(); return false;}
		if(!$('contents').value) {new MessageBox(MessageBox.TYPE_MESSAGE, '内容不能为空', '错误', {}); return false;}
		if(this.checkLen($('vote_key').value) > 20) {new MessageBox(MessageBox.TYPE_MESSAGE, '互动观点最多可以10个字', '错误', {});$('vote_key').focus(); return false;}
		
		cite.cur_vote = $('vote_key').value;
		cite.share_title = $('title').value;
		if($('tag').value){
			
			if($('tag').value.indexOf(',') < 0 && $('tag').value.indexOf('，') < 0 && $('tag').value.length > 10){
//				alert('标签超过了十个字，请修改');
				new MessageBox(MessageBox.TYPE_MESSAGE, '标签超过了十个字，请修改', '错误', {});
				return false;
			}
			
			var tag = $('tag').value.replace(/，/g,',');
			var tagArr = tag.split(",");
			var flag = 0;
			if(tagArr.length >10){
//				alert('自定义标签不能超过10个');
				new MessageBox(MessageBox.TYPE_MESSAGE, '自定义标签不能超过10个', '错误', {});
				return false;
			}
			for(var key in tagArr){
				if(tagArr[key].length > 10){
//					alert(tagArr[key]+'超过了十个字，请修改');
					new MessageBox(MessageBox.TYPE_MESSAGE, tagArr[key]+'超过了十个字，请修改', '错误', {});
					flag = 1;
					break;
				}
			}
			if(flag == 1){
				return false;
			}
		}
		form.action = '/~cite.index.post';
		form.request({
			onComplete : function(transport){
				var ret = (transport.responseText).evalJSON();
				if(ret.status == 'sucesss'){
					cite.newUri = ret.url;
					cite.share();
//					location.href=ret.url;
				}else{
					form.enable();
					new MessageBox(MessageBox.TYPE_MESSAGE, ret.msg, '错误', {});
//					ErrorTips.add(ret.id, 'warning', ret.msg,{width:'270px'});
				}
			}
		});
		form.disable();
		return false;
	},
	//删除转帖
	del_cite : function(id){
		new MessageBox(MessageBox.TYPE_OK_CANCEL,'确定要删除吗？','',{
			ok:function(){
				if(!id){
//					alert('非法操作！');
					new MessageBox(MessageBox.TYPE_MESSAGE, '参数错误', '错误', {});
				}else{
					new Ajax.Request("/~cite.index.delcite",{
						method : 'post',
						parameters : 'id='+id,
						onComplete : function(transport){
							var ret = (transport.responseText).evalJSON();
							if(ret.status == 'success'){
								new MessageBox(MessageBox.TYPE_MESSAGE, ret.msg, '操作成功', {close : function(){location.href = ret.url;}});
								
							}else{
								new MessageBox(MessageBox.TYPE_MESSAGE, ret.msg, '错误', {});
							}
						}
					});
				}
				return false;
			},
			cancel:function(){
				return false;
			}
		});
		return false;
	},
	
	//缩略图
	show_pic : function(obj){
		var max_w = 130;
		var max_h = 96;
		
		var img = obj.descendants()[0];
		
		var w = img.width;
		var h = img.height;
		if (w >= h && w > max_w){
			img.width = max_w;
		}else if (w < h && h > max_h){
			img.height = max_h;
		}
		if (img.height < max_h){
			img.style.marginTop = parseInt((max_h - img.height)/2)+'px';
		}
	},
	//缩略图
	show_pic2 : function(obj){
		var max_w = 130;
		var max_h = 96;
		
		var img = obj;
		
		var w = img.width;
		var h = img.height;
		if (w >= h && w > max_w){
			img.width = max_w;
		}else if (w < h && h > max_h){
			img.height = max_h;
		}
		if (img.height < max_h){
			img.style.marginTop = parseInt((max_h - img.height)/2)+'px';
		}
	},
	
	checkLen : function(str){
		return  str.replace(/[^\x00-\xff]/g, "**" ).length;
	},
	
	//复制链接
	copyToClipboard : function(url) {
		if(navigator.userAgent.indexOf("Chrome")>0){
			new MessageBox(MessageBox.TYPE_MESSAGE, '被浏览器拒绝，您所用浏览器的安全策略禁止用javascript访问剪贴板，请手动复制', '错误', {});
			return false;
		}
		
		txt = $(url).value;
		document.getElementById(url).select();
		if(window.clipboardData) { 
			window.clipboardData.clearData(); 
			window.clipboardData.setData("Text", txt); 
		} else if(navigator.userAgent.indexOf("Opera") != -1) { 
			window.location = txt;
		} else if (window.netscape) {
			try { 
				netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); 
			} catch (e) { 
				new MessageBox(MessageBox.TYPE_MESSAGE,"被浏览器拒绝！\n请在浏览器地址栏输入'about:config'并回车\n然后将'signed.applets.codebase_principal_support'设置为'true'", '失败', {close: function(){document.getElementById(url).select();}});
			} 
			var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
			if (!clip) 
			return; 
			var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable); 
			if (!trans) 
			return; 
			trans.addDataFlavor('text/unicode'); 
			var str = new Object(); 
			var len = new Object(); 
			var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString); 
			var copytext = txt; 
			str.data = copytext; 
			trans.setTransferData("text/unicode",str,copytext.length*2); 
			var clipid = Components.interfaces.nsIClipboard; 
			if (!clip) 
			return false; 
			clip.setData(trans,null,clipid.kGlobalClipboard);
		}
		ErrorTips.add('copy-url', 'friendly', '复制成功！');
	},
	
	confirm_url : function(url){
		if(url.search(/178.com/i) == -1 && url.search(/ngacn.cc/i) == -1 && url.search(/sc2.cc/i) == -1){
			new MessageBox(MessageBox.TYPE_OK_CANCEL,'为了你的电脑安全，请只打开来源可靠的网址，确定要打开么？','转帖',{
				ok : function(){
					window.open(url);
				},
				cancel:function(){return false;}
			});
		}else{
			window.open(url);
		}
	},
	
	//对flash进行缩放
	formatFlash : function(){
		var embeds = $$('embed');
		var flashMaxW = 560;
		var flashMaxH = 490;
		embeds.each(function(item){
			if(item.width >= item.height){
				if(item.width > flashMaxW){
					item.width = flashMaxW;
					item.height = flashMaxH;
				}
			}else{
				if(item.height > flashMaxH){
					item.height = flashMaxH;
					item.width = flashMaxW;
				}
			}
		});
	}
});
