/*
---

script: UI.js

...
*/
/*
@author:JuneWen
@date:2010-07-02
修改alert的默认效果
*/
var alert_lock = 0;
window.alert=function(text){
	// add by Zhang Junhua, 防止出现一堆提示
	if ( alert_lock == 1 ) return ;
	alert_lock = 1;
	text = new String(text);
	var delay_destroy = 3000;//多少毫秒以后消失效果
	var delay = 1000;//效果持续长度，毫秒
	var divs = $('commontip');
	if(!divs){
		divs = new Element('div',{'id':'commontip','style':'display:block;position:absolute;top:'+getPadding()+'px;opacity:100;'});
		$$('body')[0].insertBefore(divs, $$('body')[0].firstChild);
	}
	var div = new Element('div',{html:'<a href="javascript:;" onclick="window.alert.close(this);" class="shut" title="关闭"></a>'+text,'style':'margin:0;padding:0;display:block;background-color:#FFFFDB;border-bottom:1px solid #D9D9D9;height:36px;line-height:36px;position:relative;z-index:'+(1000+divs.getChildren().length)});
	divs.adopt(div);
	//divs.insertBefore(div, divs.firstChild);
	window.addEvent('scroll', function(){
		divs.setStyle('top', getPadding());
	});

	new Fx.Tween(div, {duration: 'long'}).start('marginTop',-div.getHeight(),  0);
	setTimeout(function(){new Fx.Tween(div, {duration: 'long'}).start('marginTop', 0, -div.getHeight());}, delay_destroy);
	setTimeout(function(){div.destroy();window.removeEvent('scroll');alert_lock=0;}, delay_destroy+delay);
	return false;

	function getPadding()
	{
		return document.documentElement.scrollTop?document.documentElement.scrollTop:document.body.scrollTop;
	}

};
window.alert.close=function(obj)
{
	$(obj).getParent().destroy();
}
//==
if ($type(ZN)!='object')
{
	var ZN = {};
}

ZN.UI = { version: '1.0' };

ZN.UI.show_loading = function(node)
{
	ZN.UI.show_layer($('layer_loading'), $(node));
}

ZN.UI.hide_loading = function()
{
	$('layer_loading').hide();
}

ZN.UI.show_layer = function(layer, node)
{
	if (!node)
	{
		node = document.body;
	}

	layer.setStyles({
		width	: node.clientWidth,
		height	: node.clientHeight
	});

	var k = layer.position({
	  relativeTo: node
	});

	layer.show();

	return true;
}

//显示遮罩
ZN.UI.show_mask = function()
{
	var el = $('layer_mask');
	var num = (el.get('maskcount')||'0').toInt();
	if (num<0) { num = 0; }

	el.set('maskcount', num+1);
	el.show();

	ZN.UI.resize_mask(el);
}

//隐藏遮罩
ZN.UI.hide_mask = function()
{
	var el = $('layer_mask');
	var num = (el.get('maskcount')||'0').toInt();

	if (num>0)
	{
		el.set('maskcount', --num);
	}

	if (num>0){
		return;
	}

	el.hide();
}

//重设遮罩宽高
ZN.UI.resize_mask = function()
{
	var obj = $('layer_mask');

	if (!obj.isDisplayed())
	{
		return;
	}

	ZN.UI.show_layer(obj); return;

	var left = 0, top = 0, width = document.body.scrollWidth, height = document.body.scrollHeight;

	obj.setStyles({
		left: left,
		top: top,
		width: width,
		height: height
	});
}

//放大图片
ZN.UI.pic_zoomin = function(e)
{
	e = e || window.event;
	var pic = e.target || e.srcElement;
	var node = pic.getParent().getNext();
	var err_load = false;

	if (!node.getChildren('img').length)
	{
		ZN.UI.show_loading(pic);

		var img = $(new Image());
		img.src = pic.src.replace('.thumb.jpg', '');

		img.className = 'pic2';
		img.setStyle('cursor', '-moz-zoom-out');

		node.adopt(img);

		img.addEvent('load', function(e){
			ZN.UI.hide_loading();
			this.addEvent('click', ZN.UI.pic_zoomout);

			if (typeof pic_max_width == 'number')
			{
				var w = this.width;
				var h = this.height;

				if (w > pic_max_width)
				{
					scale = w / pic_max_width;
					w = Math.floor(w/scale);
					h = Math.floor(h/scale);

				}

				this.setStyles({
					width: w,
					height: h
				});
			}

			pic.getParent().hide();
			node.show();
		});

		img.addEvent('error', function(){
			err_load = true;
			node.empty();
		});
	}else{
		pic.getParent().hide();
		node.show();
	}
}

//缩小图片
ZN.UI.pic_zoomout = function(e)
{
	e = e || window.event;
	var pic = e.target || e.srcElement;
	var node = pic.getParent().getPrevious();

	pic.getParent().hide();
	node.show();
}
//add by zmx. tmp 模板对象， obj 内容对象
ZN.UI.tmp = function(tmp,obj)
{
	var newone = tmp.clone().cloneEvents(tmp);
	var html = newone.get('html');
	newone.set('html',html.substitute(obj,/#([^#]+)#/g));
	return newone;
}
//收起右侧block块 add by zmx.
ZN.UI.toggle_sidebox = function(a,b){
	var a = $(a);
	if(a){
		a.getElement('span').toggleClass('open_btn').toggleClass('close_btn');;
		var el = a.getParent('div.sidebox').getElement('.block_list');
		if (el)
		{
			el.set('slide', {
								//open : false,
							    duration: 'long',
							    transition: 'bounce:out'
							});
			if(b){
				el.slide('hide');
			}else{
				el.slide('toggle');
			}
			//el.replaces(el.getParent());
		}else{
			return false;
		}
	}else{
		return false;
	}
}
ZN.UI.getTextAreaHeight=function (oNode)
{
	oNode=$(oNode);
	if(oNode.defaultHeight==null)
	{
		oNode.defaultHeight=oNode.getStyle("height").toInt();
	}
	var snapHeight;
	if(Browser.Engine.trident)
	{
		snapHeight=Math.max(oNode.scrollHeight,oNode.defaultHeight)
	}else
	{
		var textArea=$("_____textarea_____");
		if(textArea==null) {
			textArea = oNode.clone();
			textArea.id="_____textarea_____";
			textArea.inject($(document.body));
		}
		if(textArea.currentTarget!=oNode)
		{
			textArea.style.top="-1000px";
			textArea.style.height="0px";
			textArea.style.position="absolute";
			textArea.style.overflow="hidden";
		}
		textArea.value=oNode.value;
		snapHeight=Math.max(textArea.scrollHeight,oNode.defaultHeight);
		textArea.currentTarget=oNode
	}return snapHeight
};
ZN.UI.check = function(textarea){
	return;
	var ta = $(textarea);
	var nMaxHeight = 200;
	var nSnapHeight=ZN.UI.getTextAreaHeight(ta);
	if(nSnapHeight>nMaxHeight)
	{
		if(ta.style.overflowY==="hidden")
		{
			ta.style.overflowY="auto"
		}
	}else
	{
		if(ta.style.overflowY==="auto")
		{
			ta.style.overflowY="hidden"
		}
	}
	ta.style.height=Math.min(nMaxHeight,nSnapHeight)+"px"
}

//显示股票悬浮提示框
ZN.UI.show_sotck_tip = function(e){
	e = e || window.event;
	var obj = e.target || e.srcElement;
	var position = obj.getPosition();

	var stock = obj.get('rel');
	if (!stock || !stock.length) return;
	
	var div = $('div_zn_stock_a');
	var x0 = position.x, y0 = position.y + 20;
	if (!div)
	{
		div = new Element('div');
		div.set('id', 'div_zn_stock_a');
		div.setStyles({ 
			'position'	: 'absolute',
			'left'		: x0,
			'top'		: y0,
			'display'	: '',
			'width'		: '250px',
			'height'	: '125px',
			'zIndex'	: 1000,
			'border'	: 'solid 1px gray',
			'backgroundColor': 'white'
		}); 
		
		var img = new Image();
		div.adopt(img);				
		$(document.body).adopt(div);
	}else{
		div.setStyles({
			'left'		: x0,
			'top'		: y0,
			'display'	: ''
		});

		var img = div.getElement('img');
		if (!img)
		{
			var img = new Image();
			div.adopt(img);
		}
	}
	
	ZN.UI.show_loading(div);
	
	img.src = "http://t.zhangniu.com/pic/stock/1/" + stock + ".png?" + (new Date().valueOf());	
	$(img).addEvent('load', function(){
		ZN.UI.hide_loading(div);
	});
}

//隐藏股票悬浮提示框  
ZN.UI.hide_sotck_tip = function(e){
	var div = $('div_zn_stock_a');
	if (!div) { return; }
	
	ZN.UI.hide_loading(div);
	div.setStyle('display', 'none');
}

//functions

			//创建新风声 json
			function create_new_t(t){
				var tmp = $('slitmp');
				var newli = tmp.clone().cloneEvents(tmp);

				newli.set('id','sli'+t.sowid);//id
				newli.getElement('blockquote').destroy();//非转发
				var html = newli.get('html');
				newli.set('html',html.substitute(t,/#([^#]+)#/g));


				var avatar = newli.getElement('img');
				if(avatar) {
					avatar.addEvent('error',function(){
						this.onerror=null;
						this.src=img_path + '/images/noavatar_small.gif'
					});
				}
				if(t.attached == 0){//附件
					try{
						newli.getElement('p').getNext('div').destroy();
					}catch(e){}
				}
				newli.setStyle('display','');//可见
				return newli;
			}
			//弹出窗口默认事件
			function closedlg(dlg_id){
				$(dlg_id).dispose();
			}
			//制造评论列表
			function create_t_com_list(coms){

				var newlist = ZN.UI.tmp($('sowcomtmp'),coms);
				var newul  = newlist.getElement('ul');
				coms.data.each(function(item,index){
					var litmp = create_t_com_li(item);;
					//id
					litmp.inject(newul);
				});
				newlist.setStyle('display','');
				return newlist;
			}
			function create_t_com_li(com){
				var litmp = ZN.UI.tmp($('sowcomlitmp'),com);
				litmp.setStyle('display','');
				//avatar
				var avatar = litmp.getElement('img');
				if(avatar) {
					avatar.addEvent('error',function(){
						this.onerror=null;
						this.src=img_path+'/images/noavatar_small.gif'
					});
				}
				return litmp;
			}
			//对话
			function showComment(it){
				it.dlgid = 'com'+it.sowid;
				if($(it.dlgid)){$(it.dlgid).dispose();return;}
				if($('relay'+it.sowid))$('relay'+it.sowid).dispose();
				it.note = '评论  <span class="gray6"><strong>'+it.name+'</strong></span> ：';
				it.btn = '发 送';
				//从模板制造对话框
				var combox = ZN.UI.tmp($('dialoguetmp'),it);
				combox.setStyle('display','');//可见
				combox.set('id',it.dlgid);//id
				//获取评论
				var data = {
			            'sowid': it.sowid + ''
				};
				//获取评论
				new Request.JSON({
					url:'/submit/getcomments',
					method:'post',
					onRequest:function(){
					},
					onSuccess: function(comments,commentstxt){
						if (!comments) { alert(commentstxt);  return 0; }
						if (comments.comments > 0 ){//如果有评论则显示之
							var list = create_t_com_list(comments);
							list.getElement('ul').inject(combox);
							list.getElement('div.rf').inject(combox);
						}
					},
					onFailure: function(ts){
						alert('failed' + ts);
					}
				}).post(data);
				//添加字数提示
				var textarea = combox.getElement('textarea');
				textarea.addEvent('keyup',function(){//输入框数字
					($(this).value.length < input_box_max) ?
					combox.getElement('div.words').set('html','还能输入<strong>' + (input_box_max - $(this).value.length) + '</strong>字') :
					combox.getElement('div.words').set('html','已超出<strong>' + ($(this).value.length - input_box_max ) + '</strong>字');

				});
				textarea.value = '';
				//添加发送方法
				combox.getElement('a.btn_send').addEvent('click',function(){//发送表单
					//alert('fasong');//发送成功 提示下？
					if(textarea.value.length > input_box_max){
						//
						alert("字太多了");
						return;
					}
					data.commentsubmit = true;
					data.formhash = formhash;
					data.message = textarea.value;
					//post 请求
					var p = new Request.JSON({
						url:'/submit',
						method:'post',
						onRequest:function(){
							//alert('sending');
						},
						onSuccess: function(t,txt){
							//创建一个新的评论添加在列表最上面
							if (!t) { alert(txt);  return 0; }
							if(combox.getElement('ul')){
								var new_sent_com = create_t_com_li(t);
								new_sent_com.inject(combox.getElement('ul'),'top');
							}else{//是第一个
								var cdata = {"commentnum":0,"sowid":t.sowid};
								cdata.data = [t];
								var new_sent_com = create_t_com_list(cdata);
								new_sent_com.getElement('ul').inject(combox);
								new_sent_com.getElement('div.rf').inject(combox);
							}
							textarea.value = '';
						},
						onFailure: function(t){
							//alert('failed' + t);
						}
					});
					p.post(data);
					//发成功后添加最新的一条评论，不关闭
				});

				combox.injectAfter($('sli' + it.sowid).getElement('div.pubinfo'));
			}
			//转发
			function showRelay(it){
				//可以更简化，从a找到li然后获取id 和name
				it.dlgid = 'relay'+it.sowid;
				if($(it.dlgid)){$(it.dlgid).dispose();return;}
				if($('com'+it.sowid))$('com'+it.sowid).dispose();
				//原风声
				var tli = $('sli' + it.sowid);
				if(tli.getElement('blockquote')){
					var tm = tli.getElement('blockquote').getElement('p').clone();
					tm.getLast('a').destroy();//删掉多出的a
				}else{
					var tm = tli.getElement('p').clone();
				}
				//发布者说的话，如果是转发了的 需要去获取原始风声  TODO
				if(tm.getElement('a'))
					tm.getElement('a').destroy();//删掉多出的a
				it.note = '转发 <span class="gray6"><strong>'+it.name+'</strong></span> '+tm.get('text');
				it.btn = '转 发';

				var combox = ZN.UI.tmp($('dialoguetmp'),it);
				combox.setStyle('display','');//可见
				combox.set('id',it.dlgid);//id
				combox.getElement('div.arrow').setStyle('left',356);

				var textarea = combox.getElement('textarea');
				var count = combox.getElement('div.words');
				textarea.addEvent('keyup',function(){//输入框数字
					($(this).value.length < input_box_max) ?
					count.set('html','还能输入<strong>' + (input_box_max - $(this).value.length) + '</strong>字') :
					count.set('html','已超出<strong>' + ($(this).value.length - input_box_max ) + '</strong>字');
				});
				textarea.value = '';
				var btn = combox.getElement('a.btn_send');
				//btn.getElement('span').set('text','转 发');
				btn.addEvent('click',function(){//发送表单
					//alert('fasong');发送成功 提示下？
					if(textarea.value.length > input_box_max){
						//
						alert("字太多了");
						return;
					}

					var data = {
						'relaysubmit':true,
			            'formhash':formhash,
			            'sowid': it.sowid + ''
					};
					data.message = textarea.value;
					//post 请求
					var p = new Request.JSON({
						url:'/submit',
						method:'post',
						onRequest:function(){
							//alert('sending');
						},
						onSuccess: function(nt,txt){
							if (!nt) { alert(txt);  return 0; }
							if(nt.ok) {
								//结果处理
								var new_t = create_new_relay_t(nt);
								new_t.inject('wind_list','top');

								new_t.addEvents({
									'mouseenter': function(){
										$(this).addClass("hover");
									},
									'mouseleave': function(){
										var that = $(this);
										var tid = that.get('id').split('sli');
										if($('com'+tid[1])||$('relay'+tid[1])) return;
										that.removeClass("hover");
									}
								});

								new_t.set('slide', {
								    duration: 'long',
								    transition: 'linear'
								});
								new_t.slide('hide').slide('in');
								/*去掉外层div*/
								(function(){
									new_t.replaces(new_t.getParent());
								}).delay(5000);
				            }else{//提交失败处理
								alert('failed');
				            }
						},
						onFailure: function(t){
							//alert('failed' + t);
						}
					});
					p.post(data);


					//转发数字加1

					var ctrl_link = tli.getElement('div.lf');
					var relay_span = ctrl_link.getElements('span');
					if($chk(relay_span[0])) {
						relay_span.set('text',((relay_span.get('text') + '').toInt() + 1));
					}else{
						ctrl_link.set('html',(ctrl_link.get('html') + '&nbsp;本文已被转发<span>1</span>次'));
					}
					//var relay_num = ctrl_link.get('text').match(/\d+/);//转发数字
					//relay_ar[1].nextSibling.data = '('+((relay_num + '').toInt() + 1)+')';


					combox.dispose();
				});
				combox.injectAfter(tli.getElement('div.pubinfo'));
			}
			//创建新转发了的风声 json
			function create_new_relay_t(t){
				var newli = ZN.UI.tmp($('slitmp'),t);
				newli.set('id','sli'+t.sowid);//id

				newli.getElement('p').getNext('div').destroy();//删除第一个附件位置

				var avatar = newli.getElement('img');
				if(avatar) {
					avatar.addEvent('error',function(){
						this.onerror=null;
						this.src=img_path+'/images/noavatar_small.gif'
					});
				}



				if(t.attached1 == 0){//附件
					newli.getElement('blockquote').getElement('p').getNext('div').destroy();
				}

				newli.setStyle('display','');//可见
				return newli;
			}

			//收藏
			function t_collect(a,t){
				var a = $(a);
				if('已收藏' == a.get('text'))return;
				/*
				@author:JuneWen
				@date:2010-07-02
				增加取消收藏
				*/
				if(t.favorite){
					new Request.JSON({
						url:'/submit/uncollect/?tid='+t.sowid,
						type:'get',
						onSuccess:function(json){
							if(typeof(json)!='undefined'&&json.result){
								var li = a.getParent('li');
								var slide = new Fx.Slide(li, {
									duration: 'long'
								}).toggle();
								new Fx.Tween(li, {
									duration: 'long'
								}).start('opacity', 0);
								setTimeout(function(){li.destroy();}, 1000);
							}else{
								this.error = typeof(json)!='undefined'?json.error.toString():'操作失败';
								this.onFailure();
							}
						},
						onFailure:function(){
							alert(typeof(this.error)=='undefined'?'操作失败':this.error);
						}
					}).get();
					return;
				}
				//==
				//风声id 为 t.sowid
				var data = {
					'collectsubmit':true,
		            'formhash':formhash,
		            'id': t.sowid + ''
				};
				//post 请求
				var p = new Request.JSON({
					url:'/submit',
					method:'post',
					onSuccess: function(t,txt){
						a.set('text','已收藏');
					}
				});
				p.post(data);
			}
			//删除风声
			function t_del(t){
				//风声id 为 t.sowid
				var data = {
					//'deletesubmit':true,
		            'formhash':formhash,
		            'sowid': t.sowid + ''
				};
				//post 请求
				var p = new Request.JSON({
					url:'/submit/delt',
					method:'post',
					onSuccess: function(t,txt){
						if (!t) {
							//alert(txt);
							return 0;
						}
						//删除
						if(t.sowid != 0) {
							$('sli' + t.sowid).dispose();
						}
						//更新我的风声的数字
						var my_t_num = $('my_t_num');
						if(my_t_num) {
							my_t_num.set('html',my_t_num.get('html').toInt() - 1);
						}
					}
				});
				p.post(data);
			}

