$(document).ready(function(){
	var ctx = $("#ctx").val();
	/** 实现pv,uv,点击数，曝光数，收入样式 **/
	if($("#chartDivs").attr("value") == "total"){
		initDataFrameOrLender($("#dataFrame0"),$("#linechart0"),"dataFrame0","dataFrame_change",$("#chartDivs div.linechart"));
    }else{
    	initDataFrameOrLender($("#chartLender0 span.chartLender_box"),$("#linechart0"),"chartLender0","chartLender_change",$("#chartDivs div.linechart"));
    }
	
	function initDataFrameOrLender(defaultElemdObj,defaultChartObj,defaultElemdValue,className,chartObjs){
		if($('#dataFrame').val() == ""){
			defaultElemdObj.addClass(className);
			defaultChartObj.show();
			$('#dataFrame').val(defaultElemdValue);
			chartObjs.each(function(i){
				if(i != 0){
					$(this).hide();
				}
			});
		}
	}
	
	$("#content_dataFrame .dataFrame").click(function(){
		 $(this).addClass('dataFrame_change').siblings('.dataFrame_change').removeClass('dataFrame_change');
		 var value = $(this).attr("id");
		 $("#dataFrame").val(value);
		 var index = value.charAt(value.length - 1);
		 $("#linechart"+index).show();
		 $("#chartDivs div.linechart").each(function(i){
			if(i != index){
				$(this).hide();
			}
		});
	});
   
   $("#content_dataFrame .dataFrame").each(function(i){
		var value = $(this).attr("id");
		if($("#dataFrame").val() == value){
			$(this).addClass('dataFrame_change').siblings('.dataFrame_change').removeClass('dataFrame_change');
			$("#linechart"+i).show();
		}else{
			$("#linechart"+i).hide();
		}
   });
	
   $("#content_chartLender .chartLender_name").each(function(i){
		var value = $(this).attr("id");
		if($("#dataFrame").val() == value){
			$(this).find("span.chartLender_box").addClass('chartLender_change').siblings('.chartLender_change').removeClass('chartLender_change');
			$("#linechart"+i).show();
		}else{
			$("#linechart"+i).hide();
		}
	});
   
   $("#content_chartLender .chartLender_name").click(function(){
	   	$(this).find(".chartLender_box").addClass('chartLender_change');
		var value = $(this).attr("id");
		$("#content_chartLender .chartLender_name").each(function(i){
			if($(this).attr("id") != value){
				$(this).find(".chartLender_box").removeClass('chartLender_change');
			}
		});
		$("#dataFrame").val(value);
		var index = value.charAt(value.length-1);
		$("#linechart"+index).show();
		$("#chartDivs div.linechart").each(function(i){
			if(i != index){
				$(this).hide();
			}
		});
	});
   
    /** 实现chart图表 **/
	function getDate(tm){ 
		var tt=new Date(parseInt(tm)).toLocaleDateString();
		return tt; 
	}
	function getele1(){
		try{
		  	var d=document.getElementsByName("hr");
		  	var c=[];
		  	
		  	for(i=0;i<=d.length;i++){
		  		c[i]=d[i].childNodes[0].nodeValue;
		  	}
		}catch(e){}
		return c;
	}
	function initChart_homePage(){
		var datePicker = $("#dateRangePicker").val().split(" to ");
		var startDate = datePicker[0];
		var endDate = datePicker[1];
		if(startDate==endDate){
			var m=getele1();
			n=24;
			var color=[];
			for(i=0;i<n;i++){
				color[i]='red';
			}
			n1=n*6;
			var xlabel=[];		
			var j=0;
			for(i=0;i<n1;i+=6){
				xlabel[j]=m[i];
				j++;
			}
			//取y轴
			var uv=[];
			var j=0;
			for(i=2;i<n1;i+=6){
				uv[j]=parseFloat(m[i]);
				j++;
			}
			var pv=[];
			var j=0;
			for(i=1;i<n1;i+=6){
				pv[j]=parseFloat(m[i]);
				j++;
			}							
			var adbaoguang=[];
			var j=0;
			for(i=3;i<n1;i+=6){		
				adbaoguang[j]=parseFloat(m[i]);
				j++;
			}
			var adclick=[];
			var j=0;
			for(i=4;i<n1;i+=6){
				adclick[j]=parseFloat(m[i]);
				j++;
			}
			var shouru=[];
			var j=0;
			for(i=5;i<n1;i+=6){
				shouru[j]=parseFloat(m[i]);
				j++;
			}	
			setinterval=1;				
		}else{
			var selectedZoneId=$("#selectedZoneId").val();
			if(selectedZoneId==null || selectedZoneId==""){selectedZoneId=-1}
			var dateRangePicker=$("#dateRangePicker").val();
			url = ctx+"/back/main/ad/operator/operator-report/listChartData?dateRangePicker="+dateRangePicker+"&selectedZoneId="+selectedZoneId;
			var pv = [];
			var uv = [];
			var adbaoguang = [];
			var adclick = [];
			var shouru = [];
			var xlabel = []
			var k = 0;
					
 			$.ajaxSettings.async = false; //getJSON同步执行
			$.getJSON(url, function(data) {
				$.each(data, function(key, val) {
					xlabel[k] = val.reportDate;
					xlabel[k] = getDate(xlabel[k]);
					pv[k] = val.pv;
					uv[k] = val.uv;
					adbaoguang[k] = val.impression;
					adclick[k] = val.click;
					shouru[k] = val.income;
					k++;
				});	
			});	
			//alert(xlabel);
			setinterval=parseInt(xlabel.length/10);							
		}
		var chartDivs = $("#chartDivs").find("div").length;
		var names = ['PV','UV','广告曝光数','广告点击数','收入'];
		var values = [pv,uv,adbaoguang,adclick,shouru];
		for(var i = 0;i<chartDivs;i++){
			getHighchart_homePage($("#linechart"+i),names[i],names[i],values[i],xlabel);
		}
	}
	function getHighchart_homePage(obj,title,name,value,xlabel){
		obj.highcharts({
	        title: {
	            text: title,
	        },
	        xAxis: {
	            categories: xlabel,
	            tickInterval: setinterval 
	        },
	        yAxis: {
	            plotLines: [{
	                value: 0,
	                width: 1,
	               color: '#36aeea'
	           }]
	        },
	        legend: {
	           layout: 'vertical',
	            align: 'right',
	          verticalAlign: 'middle',
	           borderWidth: 0
	        },
	        series: [{
	            name: name,
	            data: value,
	            color:'#36aeea'
	        }]
	    });
	}
	
	function getele(){
		try{
			var b=document.getElementsByTagName("td");	  				
				var c=[];	  			
  			for(i=0;i<b.length;i++){  
  				c[i]=b[i].childNodes[0].nodeValue;
  			}	
		}
		catch(e){}
		return c;
	}

	function initChart_other(){
		m=getele();
		n=$("#listSize").val();
		var color=[];
		for(i=0;i<n;i++){
			color[i]='#36aeea';
		}
		n2=10;
		n1=n*n2;
		var lll = getData_other(m,n1,n2,1);
		var pv = getData_other(m,n1,n2,2);
		var uv = getData_other(m,n1,n2,3);
		var adbaoguang = getData_other(m,n1,n2,4);
		var adtianchong = getData_other(m,n1,n2,5);
		var adclick = getData_other(m,n1,n2,6);
		var adclickl = getData_other(m,n1,n2,7);
		var ecpm = getData_other(m,n1,n2,8);
		var shouru = getData_other(m,n1,n2,9);
		var chartDivs = $("#chartDivs").find("div").length;
		var names = ['浏览量占比','PV','UV','广告曝光数','广告填充率','广告点击数','广告点击率','eCPM','收入'];
		var values = [lll['value'],pv['value'],uv['value'],adbaoguang['value'],adtianchong['value'],adclick['value'],adclickl['value'],ecpm['value'],shouru['value']];
		var xlabels = [lll['xlabel'],pv['xlabel'],uv['xlabel'],adbaoguang['xlabel'],adtianchong['xlabel'],adclick['xlabel'],adclickl['xlabel'],ecpm['xlabel'],shouru['xlabel']];
		for(var i = 0;i<chartDivs;i++){
			if(i==0){
				getHighchart_other($("#linechart"+i),names[i],names[i],values[i],xlabels[i],"of total","{point.y:.2f}%",color);
			}else if(i==4 || i==6){
				getHighchart_other($("#linechart"+i),names[i],names[i],values[i],xlabels[i],"","{point.y:.2f}%",color);
			}else{
				getHighchart_other($("#linechart"+i),names[i],names[i],values[i],xlabels[i],"","{point.y:.2f}",color);
			}
		}
	}
	
	function getData_other(m,n1,n2,index){
		var result = new Object();
		var xlabel=[];
		var j=0;
		for(i=0;i<n1;i+=n2){
			xlabel[j]=m[i];
			j++;
		}
		var value=[];
		var j=0;
		for(i=index;i<n1;i+=n2){
			if(m[i]!=null){
				value[j]=parseFloat(m[i]);
			}
			j++;
		}
		
		//排序
		var temp = "";
		var tempxlabel = "";
		for (var a = 0; a < value.length; a++){//最多做n-1趟排序  
            for(var b = 0 ;b < value.length - a; b++){
                if(value[b] < value[b + 1]){ //把小的值交换到后面  
                	temp = value[b];  
                	value[b] = value[b + 1];  
                	value[b + 1] = temp; 
                	tempxlabel = xlabel[b];
                	xlabel[b] = xlabel[b + 1];
                	xlabel[b + 1] = tempxlabel;
                }  
            }      
		}
		result['xlabel'] = xlabel;
		result['value'] = value;
		return result;
	}
	
	function getHighchart_other(obj,title,name,value,uselllxlabel,defaultValue,defaultParsent,color){
		obj.highcharts({
			chart: {
				type: 'column'
			},
			title: {
				text: title
			},
			xAxis: {
				categories: uselllxlabel
			},       
			legend: {
				enabled: false
			},
			plotOptions: {
				series: {
					borderWidth: 0,
					pointWidth: 30,
					dataLabels: {
						enabled: true
			       
					}
				}
			},
			plotOptions: {
				series: {
				    borderWidth: 0,
				     pointWidth: 30,
				     dataLabels: {
				    	 enabled: true,
				        format: defaultParsent
				    }
				}
			},
			tooltip: {
				headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
				pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>'+defaultParsent+'</b> '+defaultValue+'<br/>'
			},
			series: [{
				name: name,
				colorByPoint: true,
				colors:color,
				data: value
			}]       
		});   
	}

	/** 实现日期选择的样式 **/
	$('#dateChoose_span a').click(function(e){
       	inputForDate(e,$(this),$('#dateRangePicker'));
        $("#dateTab").val($(this).attr("value"));
        $(this).addClass('dateChange').siblings('.dateChange').removeClass('dateChange');
    });
   
    $('#dateRangePicker').dateRangePicker();
    if($('#dateRangePicker').val() == ""){
		$('#dateRangePicker').val(getlastDate(1)+" to "+getlastDate(1));
		$("#dateChoose_span #yesterday").addClass('dateChange');
		$("#dateTab").val("yesterday");
	}
    if($("#chartDivs").attr("value") == "total"){
    	initChart_homePage();
    }else{
    	initChart_other();
    }
	$('#dateChoose_span a').each(function(){
		var value = $(this).attr("value");
		if($("#dateTab").val() == value){
			$(this).addClass('dateChange');
		}
	});
	//点击日期控件的按钮时，去掉前面时间标签的样式
	$(".apply-btn").click(function(){
		if(!$(this).hasClass("disabled")){
			$("#dateTab").val("");
			$('#dateChoose_span a').removeClass('dateChange');
			$('#dateRangePicker').val($(".start-day").text() +" to "+$(".end-day").text());
		}
	});

 	//控制页码
    $('#pageDiv .pagination ul li a[href]').click(function(){
		var _page = $(this).attr('href').substr(1);//获取当前点击的页码
		console.log(_page);
		var _form = $('#myform');
		_form.find('input:hidden[name="page"]').val(_page);//将当前点击的页码赋值给搜索form中页码输入框
		_form.submit();
	});
    
    $("#img-city").live("click",function(){
		var img = $(this);
		var cnName = img.attr("value");
		if(img.attr("type") == "close"){
			$.ajax({
		    	type:"POST",
		    	url:ctx+"/back/main/ad/operator/operator-report/city",
		    	data:{cn:cnName,selectedOperatorId:$("#selectedOperatorId").val(),dateRangePicker:$("#dateRangePicker").val()},
		    	success:function(data){
		    		var html = "";
		    		if(data.length >0){
		    			for(var i = 0;i<data.length;i++){
		    				html += '<tr id='+cnName+' class="changeColor" style="background-color:#CCCCCC;">';
		    				html += '<td class="tbodyTd" style="margin-left:20px;"><img src="'+ctx+'/assets/images/defaultLeaf.gif" style="position: relative;top:-2px;left:-5px;"/>'+data[i].cn_city+'</td>';
		    				html += '<td class="tbodyTd">'+data[i].viewRate+'%</td>';
		    				html += '<td class="tbodyTd">'+data[i].pv+'</td>';
		    				html += '<td class="tbodyTd">'+data[i].uv+'</td>';
		    				html += '<td class="tbodyTd">'+data[i].impression+'</td>';
		    				html += '<td class="tbodyTd">'+data[i].fillRate+'%</td>';
		    				html += '<td class="tbodyTd">'+data[i].click+'</td>';
		    				html += '<td class="tbodyTd">'+data[i].clickRate+'%</td>';
		    				html += '<td class="tbodyTd">'+data[i].eCpm+'</td>';
		    				html += '<td class="tbodyTd">'+data[i].income+'</td>';
		    				html += '</tr>';
		    			}
		    		img.parents('tr').after(html);
		    		}
		    		img.attr("src",ctx+"/assets/images/folderOpen.gif");
		    	}     
			});	
			img.attr("type","open");
		}else if(img.attr("type") == "open"){
		    $('tr').remove("#"+cnName);//删除id为cname的所有 tr
		    img.attr("src",ctx+"/assets/images/folderClose.gif");
		    img.attr("type","close");
			//location.href = "${ctx}/back/main/ad/operator/operator-report/areal";
		}
	});
	
});

function exportExcel(tab,url,type){
	var params = "?"+tab+"=1&dateRangePicker="+$("#dateRangePicker").val();
	if(type == "back_total"){
		params += "&selectedOperatorId="+$("#selectedOperatorId").val()+"&selectedZoneId="+$("#selectedZoneId").val();
	}else{
		params += "&selectedOperatorId="+$("#selectedOperatorId").val();
	}
	$("#exportExcel").attr("href",url+params);
}

