/**
* 此文件处理一些公共的投票和顶踩以及评论等
* 只需通过html标签上配置相关属性，并载入此文件即可
* 2010-08-13 by Longbill (http://php.js.cn) 
*/


/**
* 顶踩(投票)
* 
* 包括票数显示dom和投票按钮dom
* 票数显示dom:  例如: <span rating-show="up" rating-id="10081201" rating-type="campaign">0</span>
*    其中rating-show表示要显示up还是down，如果是投票，可以只显示up
*    rating-id对应rating表里面的item_id
*    rating-type对应rating表里面的item_type的字面量，例如'campaign'表示17
* 
* 投票按钮dom:  例如 <input rating-action="up" rating-id="10081201" rating-type="campaign" type="image" ...
*    rating-action表示投票的动作是顶(up)还是踩(down)
*    可选: rating-note="重复投票的提示信息"，默认是:"请不要重复投票!"
*    其他和票数显示dom一样
*/
$(function()
{
	/**
	* 显示数据开始
	*/
	var ids = {};
	$('[rating-show]').each(function()
	{
		var t = $.trim($(this).attr('rating-type'));
		if (!ids[t]) ids[t] = [];
		ids[t].push($.trim($(this).attr('rating-id')));
	});
	
	for(var t in ids)
	{
		ids[t] = $.unique(ids[t]); //因为顶踩的id是一样的，所以要先去掉重复
		(function(t)
		{
			$.post('/ajax/rating.php?act=get&t='+Math.random(),{ ids: ids[t].join(','), 'type':t },function(data)
			{
				for(var id in data)
				{
					var _id = id.replace('key_','');
					$('[rating-show=up][rating-id='+_id+']').html(data[id][0]);
					$('[rating-show=down][rating-id='+_id+']').html(data[id][1]);
				}
			},'json');
		})(t);
	}
	
	/**
	* 投票按钮开始
	* 采用live绑定，即使新加了节点也有效
	*/
	$('[rating-action]').live('click',function()
	{
		var self = $(this);
		var note = (self.attr('rating-note')) ? self.attr('rating-note') : '请不要重复投票!';
		var up_down = (self.attr('rating-action') == 'up') ? '1':'2';
		
		if (!$.umiwi.check_vote_cookie(self.attr('rating-type'),self.attr('rating-id')))
		{
			alert(note);
			return;
		}
		
		$.post('/ajax/rating.php?act=rate&up_down='+up_down+'&t='+Math.random(),
		{
			'id' : self.attr('rating-id'),
			'type' : self.attr('rating-type')
		},function(s)
		{
			if (s == '1') //成功！
			{
				var o = $('[rating-show='+self.attr('rating-action')+'][rating-id='+self.attr('rating-id')+']');
				o.html(parseInt(o.html())+1);
				$.umiwi.set_vote_cookie(self.attr('rating-type'),self.attr('rating-id'));
			}
			else if(s ==0 )
			{
				alert("发生了错误! Rating returns 0 ");
			}
			else if(s ==2 )
			{
				alert(note);
			}
			else if(s ==3 )
			{
				alert(note+"!"); //重复顶踩的提示信息,ip限制
			}
			else if(s ==-2 ) //需要登陆
			{
				login(function()
				{
					self.trigger('click');
					close_popup();
				});
			}
			else
			{
				alert("服务器发生错误! Rating return is not number");
			}
		},'text');
	});
	
});


/**
* 彩条投票
* 
* 按钮dom : <input survey-action="up" survey-id="87" survey-limit="2" type="image" src="/images/digg_top.gif" ...
*     其中   survey-id表示survey的id    survey-action="up" 为固定写法，因为没有down!!!
* 			survey-limit 可选，表示同一个survey-id的投票最多能投几个选项(默认是1)
*     可选: rating-note="重复投票的提示信息"，默认是:"您已发表过观点，谢谢您的参与!"
* 
* 彩条dom: <td survey-show="bar" survey-width="150" survey-id="87" style="width:0px;" ...></td>
*     其中  survey-show="bar" 表示此dom为彩条， survey-width表示此条最大宽度是多少  survey-id同上
* 
* 票数dom: <span survey-show="number" survey-id="87" >0</span>  参数同上
* 
* 票数百分比dom: <span survey-show="percent" survey-id="87" >0%</span> 参数同上
*/

$(function()
{
	/**
	* 投票
	*/
	var bts = $('[survey-action=up]'), surveyIds = [];
	bts.each(function() 
	{
		var id = parseInt($(this).attr('survey-id'));
		if (surveyIds[id] == undefined) surveyIds[id] = 0;
		$(this).data('index',surveyIds[id]).data('item',id*10000 + surveyIds[id]);
		surveyIds[id] = surveyIds[id] + 1;
	});
	
	bts.click(function()
	{
		var item = $(this).data('item');
		var limit = parseInt($(this).attr('survey-limit')); //投票限制
		var id = $(this).attr('survey-id');
		var self = $(this);
		var note = (self.attr('rating-note')) ? self.attr('rating-note') : (limit > 1) ?'最多投'+limit+'票!':'您已发表过观点，谢谢您的参与!';

		if (!$.umiwi.check_vote_cookie('survey',id,limit))
		{
			alert(note);
			return;
		}
		
		
		$.post('/ajax/rating.php?act=rate&t='+Math.random(),{ 'id' : item, 'type' : 'survey' },function(s)
		{
			if (s == '1')
			{
				loadSurveyData(id);
				$.umiwi.set_vote_cookie('survey',id)
			}
			else if(s ==0 )
			{
				alert("发生了错误! Rating returns 0 ");
			}
			else if(s ==2 )
			{
				alert(note);
			}
			else if(s ==3 )
			{
				alert(note+"!"); //重复顶踩的提示信息,ip限制
			}
			else if(s ==-2 ) //需要登陆
			{
				login(function()
				{
					self.trigger('click');
					close_popup();
				});
			}
			else
			{
				alert("服务器发生错误! Rating return is not number");
			}
		},'text');
	});
	
	
	
	/**
	* 载入数据
	*/
	function loadSurveyData(id)
	{
		var ids = [];
		if (id)
		{
			$('[survey-action=up][survey-id='+id+']').each(function()
			{
				ids.push($(this).data('item'));
			});
		}
		else
		{
			$('[survey-action=up]').each(function()
			{
				ids.push($(this).data('item'));
			});
		}
		$.post('/ajax/rating.php?act=get&t='+Math.random(),{ 'ids' : ids.join(','), 'type' : 'survey' },function(data)
		{
			var dat = {};
			for(var key in data)
			{
				var i = parseInt(key.replace('key_',''))%10000;
				var id = parseInt(parseInt(key.replace('key_',''))/10000);
				if (!dat[id]) dat[id] = [];
				dat[id][i] = data[key][0];
			}
			
			
			for(var id in dat)
			{
				var arr = dat[id];
				
				var total = 0,
					max = 0,
					num,
					j;

				var bars = $('[survey-show=bar][survey-id='+id+']'),
					numbers = $('[survey-show=number][survey-id='+id+']'),
					percents = $('[survey-show=percent][survey-id='+id+']');
			
				/**
				* 找到最大的数字和总和
				*/
				for(j = 0; j < ids.length; j++)
				{
					if (!arr[j]) arr[j] = 0;
					num = parseInt(arr[j]);
					if (max < num) max = num;
					total += num;
				}
				if (max <= 0 || total <= 0) return;
				for(j = 0; j < ids.length; j++)
				{
					num = parseInt(arr[j]);
					bars.eq(j).animate({ width: parseInt(bars.eq(j).attr('survey-width')) * num / max },100);
					numbers.eq(j).html(num);
					percents.eq(j).html( (Math.round( num * 10000 / total )/100) + '%' );
				}
			
			}
		},'json');
	}
	
	loadSurveyData();
	
	
	
});



/**
* 增加一个$.umiwi命名空间
*/
if (!$.umiwi) $.umiwi = {};
/**
* 检查是否投过票，第一个参数是类型，第二个是id
*/
$.umiwi.check_vote_cookie = function(item, id,limit)
{
	if (!limit || limit <= 0) limit = 1;
	var s = $.trim($.cookie(item));
	if (!s) s = '_';
	if(s.length>4000) $.cookie(item, '', { expires: 10, path: '/'}); //add 2010-3-8
	var count = 0;
	while(s.indexOf('_'+id+'_') != -1)
	{
		count++;
		s = s.replace('_'+id+'_','_');
	}
	return (count < limit);
};
/**
* 设置投过票，第一个参数是类型，第二个是id
*/
$.umiwi.set_vote_cookie = function(item, id)
{
	var s = $.trim($.cookie(item));
	if (!s) s = '_';
	s += id + '_';
	$.cookie(item,s,{ expires: 10, path: '/'});
}

