/**
 * 二次封装envision插件
 * 添加图上方的div，用于选择显示指标和事件跨度
 */

/**
 * 图中第一部分为price,第二部分volume，第三部分为summary
 * options = {
 *  container: //画图的父容器
 * 	data:{//显示的数据
 * 		price: {data: financeData.price['fee'], label:'收入',lines:{show:true},yaxis:2,color:'red'},
  				{data: [[1300,1360],[3226256,2325262]],points:{show:true},yaxis:2},	
 * 		volume:
 * 		summary:
 * 	},
 * trackFormatter:function(n){}//自定义鼠标跟随事件
 * xTickFormatter :function(n){} //自定义x轴显示效果
 * yTickFormatter:function(n){}//自定义Y轴
 * selection: {data:{x:{},y:{}}}//限定默认选中长度
 * selectionCallback :function(){}//
 * defaults :{//图表显示参数
 * 	price:{//参数可选
 * 		config:{//@debug flotr2中的defaultoptions中的值
 * 		 mouse : {
	          track: true,
	          trackY: false,
	          trackAll: true,
	          sensibility: 1,
	          trackDecimals: 4,
	          position: 'ne'
	        },
	        yaxis : { 
	          autoscale : true,
	          autoscaleMargin : 0.05,
	          noTicks : 4,
	          showLabels : true,
	          min : 0
	        },
	        grid : {
	          verticalLines : false
	        }
 * 		}
 * 	},
 * volume:{},//类似price
 * summary:{}//类似price
 * }
 * }
 */

var financeOptions = {
  data : {//绘图数据
    price : [
    	{data: financeData.price['fee'], label:'收入',lines:{show:true},yaxis:2},
  		{data: [[1300,1360],[3226256,2325262]],points:{show:true},yaxis:2},	
  	],
    volume : {data: financeData.volume, label:'访问用户数',yaxis:2},
    summary : financeData.summary
  },
  //自定义鼠标跟随显示的数据，不写调用默认的跟随事件
  trackFormatter : function (o) {
	  function cusFormat(d){  
	  	var fix = '';
			var num = parseInt(d);
			if (d / 100000000 >= 1) {
				fix = '亿';
				num = (d / 100000000);
				num = num.toFixed(2);
			} else if (d / 10000 >= 1) {
				fix = '万';
				num = d / 10000;
				num = num.toFixed(2);
			}
			return num + fix;
	  };
 	var data = o.series.data,
      index = data[o.index][0],
      value;
 	var f=d3.time.format('%Y-%m-%d');
 	var date = new Date(financeData.summaryTicks[index].date);
 	var $checked = $('.chkbox input[type=radio]:checked');
    value = f(date) + ': '+$checked.parent().text()+':' + cusFormat(financeData.price[$checked.val()][1][parseInt(o.x)]) + ", 访问用户数: " + cusFormat(financeData.volume[1][parseInt(o.x)]);
    return value;
  },
   
  //格式化横轴，可空
  xTickFormatter : function (index) {
    var date = new Date(financeData.summaryTicks[index].date);
    return date.getFullYear() + '';
  },
  yTickFormatter:function(n){  
     return n;  
  },  
  // 默认summary选中时间长度
  selection : {
    data : {
      x : {
        min : 1200,
        max : 2000
      }
    }
  },
  selectionCallback : function(o){
  	var dateMin = new Date(financeData.summaryTicks[parseInt(o.data.x.min)].date);
  	var dateMax = new Date(financeData.summaryTicks[parseInt(o.data.x.max)].date);
  	var time = dateMin.getFullYear()+'-'+(dateMin.getMonth()+1)+'-'+dateMin.getDate()+'至'+dateMax.getFullYear()+'-'+(dateMax.getMonth()+1)+'-'+dateMax.getDate();
  	$('.show-time').text(time);
  	financeOptions.envisionSelectCallback && financeOptions.envisionSelectCallback({sTime : dateMin, eTime : dateMax});
  },
  //显示图的部分设置，显示效果主要在此配置
 
};
var headData = {
		time : '2012-12-23至2013-01-23',
		list : [
		        {label:'收入',value:'fee'},
		        {label:'PV',value:'pv'},
		        {label:'阅读用户数',value:'r_count'},
		        {label:'推荐',value:'recommend'},
		        {label:'鲜花',value:'flower'},
		        ]
}
/**
 * 股票图上方的指标选择
 * {
 * 	time : ,
 *  list : [
 *  {
 *  	label: ,
 *  	value:
 *  }, {
 *  	label: ,
 *  	value:
 *  },
 *  ]
 * }
 */
ebFrame.envisionChartHeadT = template.compile(
		'<div class="envision-head" >'+
			'<div class="fr chk-kpis"><ul>'+
				'<% for(var i=0;i<list.length;i++){ %>'+
					'<li class="fl"> '+
						'<label class="chkbox"><input class="" type="radio" name="price_index_radio" value="<%=list[i].value%>" <% if(i==0){ %>checked="checked"<% } %>/><%=list[i].label%></label>'+
					'</li>' + 
				'<% } %>'+
			'</ul></div>'+
			'<div class="fr average"><label class="chkbox"><input class="average" type="checkbox" value="average"/>显示均值线</label></div>'+
			'<span class="show-time"><%=time%></span>'+
			'<div class="clear"></div>'+
		'</div>'
	);
;(function($){
	$.fn.eb_envision = function(options){
		var $div_foot = $('<div class="envision-container"></div>');
		//var headData = options.data || {};
		$.extend(financeOptions , options);
		$(this).append(ebFrame.envisionChartHeadT(headData));
		$(this).append($div_foot);
		_bindEvents($(this));
		financeOptions.container = $div_foot[0];
		draw(financeOptions);
		return this;
	};
	function draw(opt){
		$(opt.container).html('');
		var vis ;
		vis = new envision.templates.Finance(opt);
		return this;
	};
	function _bindEvents($p){
		$('.chkbox').click(function(){
			var $checkbox = $('.chkbox input[type=radio]',$p);
			financeOptions.data.price = [];
			$.each($checkbox,function(i,n){
				if($(n).attr('checked')){
					if($(n).val()=='pv' || $(n).val()=='r_count' ){
						financeOptions.data.price.push({data: [[1300,1360],[516,608]],points:{show:true},yaxis:2});
					}else{
						financeOptions.data.price.push({data: [[1300,1360],[3226256,2325262]],points:{show:true},yaxis:2});
					}
					financeOptions.data.price.push({data:financeData.price[$(n).val()],yaxis:2,label:$(n).parent().text(),lines:{show:true}});
				}
			})
			draw(financeOptions);
		})
	}
})(jQuery)