//JQplot consts
const TITLE_FONT_SIZE = '20pt';
const FONT_FAMILY = 'Georgia';
const Y_LABEL = 'Percent';
const X_LABEL = 'Date';
const TICK_FONT_SIZE = '20pt';
const ANGLE = -60;
var fileName;
var isRisk;
var riskOptions;

function statisticPage1Ready(){
	
	proSentPage_initializePage([], "Guest", 1);
	
}

function proSentPage_initializePage(request, userName, groupId){
	showLoading();
	$.getJSON("proSentPageEng.php", request, function(data){
		hideLoading();
		fileName = data.fileName;
		isRisk = data.risk;
		riskOptions = data.riskOptions;
		if(data.asAvg){
			
			if(data.risk){
										
				makeBarChart(data.noRisk, data.high, data.medium, data.low, data.xLabelPoints, data.allAnaTxt, data.highNum, data.medNum, data.lowNum, data.noRiskNum, data.first, data.last);
				
			}else{
				
				makeChartAvg(data.title, data.points, data.proPoints, data.localProAvg, data.antiPoints, data.localAntiAvg, data.allAnaTxt, data.allEntTxt, data.allEntPro, data.allEntAnti, data.fromToDate);
				
			}
		}else{
			
			if(data.risk){
				makeBarChart(data.noRisk, data.high, data.medium, data.low, data.xLabelPoints, data.allAnaTxt, data.highNum, data.medNum, data.lowNum, data.noRiskNum, data.first, data.last);
		
			}else{
				
				makeChart(data.title, data.points, data.proPoints, data.antiPoints, data.localAntiAvg, data.localProAvg, data.xLabelPoints, data.allAnaTxt, data.allEntTxt, data.allEntPro, data.allEntAnti);
							
			}
		}
	});
}

function showLoading()
{
	$("#loadingDiv").html("<p align=center><img src='images/loader.gif' alt='loading...' /></p><p align=center><b>Please wait</b></p>").show();
	$("#ChartDiv").hide();
}
function hideLoading()
{
	$("#loadingDiv").hide();
	$("#ChartDiv").show();
}

$(document).ready(statisticPage1Ready);

function goTo(path){
	
	window.location.href = path;
}

function downLoadFile(){

	goTo("download.php?chartName=" + fileName);
	
}

function goBack(){
	window.location.href = "proSentPage.php";
}

function showInformation(fromToDate, allAnaTexts, param1, param2, param3, param4){

	if(isRisk){
		//param1 -> high priority
		//param2 -> medium priority
		//param3 -> low priority
		//param4 -> no priority

		var fullHTMLriskTable = "<table><tr><th style=\"text-align: center; width:150px; text-transform: none\">Between the following dates</th><th style=\"text-align: center; text-transform: none\">Sum of all analysed documents</th>";

		//Building the titles
		if(riskOptions.indexOf("isHigh")!= -1 )fullHTMLriskTable += "<th style=\"text-align: center; text-transform: none\">Sum of high priority</th>";		
		if(riskOptions.indexOf("isMedium")!= -1 )fullHTMLriskTable += "<th style=\"text-align: center; text-transform: none\">Sum of medium priority</th>";
		if(riskOptions.indexOf("isLow")!= -1 )fullHTMLriskTable += "<th style=\"text-align: center; text-transform: none\">Sum of low priority</th>";
		if(riskOptions.indexOf("isNoRisk")!= -1 )fullHTMLriskTable += "<th style=\"text-align: center; text-transform: none\">Sum of no priority</th>";

		fullHTMLriskTable += "<th style=\"text-align: center; text-transform: none\">Download points</th></tr><tr><td style=\"text-align: center;\">" + fromToDate + "</td><td style=\"text-align: center;\">" + allAnaTexts + "</td>";

		//building the data	
		if(riskOptions.indexOf("isHigh")!= -1 )fullHTMLriskTable += "<td style=\"text-align: center;\">" + param1 + "</td>";	
		if(riskOptions.indexOf("isMedium")!= -1 )fullHTMLriskTable += "<td style=\"text-align: center;\">" + param2 + "</td>";
		if(riskOptions.indexOf("isLow")!= -1 )fullHTMLriskTable += "<td style=\"text-align: center;\">" + param3 + "</td>";
		if(riskOptions.indexOf("isNoRisk")!= -1 )fullHTMLriskTable += "<td style=\"text-align: center;\">" + param4 + "</td>";

		fullHTMLriskTable += "<td style=\"text-align: center;\"><a id=\"btn\"><img id=\"btnImg\"></img></a></td></tr></table>";

		$("#addInfoTable").append(fullHTMLriskTable);	
	}else{
		//param1 -> sum of all entity occurrences
		//param2 -> sum of positive references
		//param3 -> sum of negative references
		if (typeof param2 !== 'boolean') {
			$("#addInfoTable").append("<table><tr><th style=\"text-align: center; width:150px; text-transform: none\">Between the following dates</th><th style=\"text-align: center; text-transform: none\">Analysed Documents</th><th style=\"text-align: center; text-transform: none\">Entity occurrences</th><th style=\"text-align: center; text-transform: none\">Positive references</th><th style=\"text-align: center; text-transform: none\">Negative references</th><th style=\"text-align: center; text-transform: none\">Download points</th></tr><tr><td style=\"text-align: center;\">" + fromToDate + "</td><td style=\"text-align: center;\">" + allAnaTexts + "</td><td style=\"text-align: center;\">" + param1 + "</td><td style=\"text-align: center;\">" + param2 + "</td><td style=\"text-align: center;\">" + param3 + "</td><td style=\"text-align: center;\"><a id=\"btn\"><img id=\"btnImg\"></img></a></td></tr></table>");
		}else{
			$("#addInfoTable").append("<table style=\"margin: auto; width:100%; height:100%;\"><tr><th style=\"text-align: center; width:150px; text-transform: none\">Between the following dates</th><th style=\"text-align: center; text-transform: none\">Analysed Documents</th><th style=\"text-align: center; text-transform: none\">Entity occurrences</th><th style=\"text-align: center; text-transform: none\">Download points</th></tr><tr><td style=\"text-align: center;\">" + fromToDate + "</td><td style=\"text-align: center;\">" + allAnaTexts + "</td><td style=\"text-align: center;\">" + param1 + "</td><td style=\"text-align: center;\"><a id=\"btn\"><img id=\"btnImg\"></img></a></td></tr></table>");
		}	
	}	
}

function addDownloadBtn(selector){

	$(selector).attr("href","javascript:downLoadFile()");
	$(selector).attr("id","btnDownload");
	$(selector).attr("type","button");
	$("#btnImg").attr("src", "images/download-icon.png");
	$("#btnImg").attr("width", "20");
	$("#btnImg").attr("onmouseover", "this.src='images/download-icon-bw.png'; this.style.cursor='hand';");
	$("#btnImg").attr("onmouseout", "this.src='images/download-icon.png';");
}

function makeBarChart(noRisk, high, medium, low, xPoints, allAnaTexts, tHigh, tMed, tLow, tNoRisk, firstDate, lastDate){

	var title = "Priority level between: " + firstDate + " and " + lastDate;

	var series = [];	
	var points = [];

	if(noRisk.length-1 > 0){
		points.push(noRisk);
		series.push({label:'No risk', color:'#85E0FF'});	
	}
	if(high.length-1 > 0){
		points.push(high);
		series.push({label:'High', color:'#FFB8B8'});
	}
	if (medium.length-1 > 0)
	{
		points.push(medium);
		series.push({label:'Medium', color:'#FFB84D'});
	}
	if (low.length-1 > 0)
	{
		points.push(low);
		series.push({label:'Low', color:'#B8FF70'});
	}
	

    var plot1 = $.jqplot('sampleDiv', points, {
    	  stackSeries: true,
    	  animate: !$.jqplot.use_excanvas,	
		  title: {
			fontFamily: FONT_FAMILY,
			text: title,
			fontSize: TITLE_FONT_SIZE
				},
        seriesDefaults:{
			pointLabels: {show: true},			        
            renderer:$.jqplot.BarRenderer
        },
        series:series,
        legend: {
            show: true,
            placement: 'outsideGrid',
            fontSize: 15
        },
        axes: {
            xaxis: {
    			labelRenderer: $.jqplot.CanvasAxisLabelRenderer,	
    			tickRenderer:$.jqplot.CanvasAxisTickRenderer,            
                renderer: $.jqplot.CategoryAxisRenderer,
                ticks: xPoints,
                label: X_LABEL,
                tickOptions:{
        			angle: ANGLE,
        			fontSize: '7pt'
        		}
            },
            yaxis: {
                pad: 1.05,
                tickOptions: {formatString: '%#.0f%', fontSize: 10},
                label:Y_LABEL,
                min:0,
                max:100
            },
					highlighter: {
				        show: true,
				        sizeAdjust: 7.5
				      },
				    cursor: {
				        show: false
				      }
        }
    });

	var fromToDate = firstDate + " -- " + lastDate;
    showInformation(fromToDate, allAnaTexts, tHigh, tMed, tLow, tNoRisk);
    addDownloadBtn("#btn");	
}

function makeChart(title, points, proPoints, antiPoints, localAntiAvg, localProAvg, xLabelPoints, allAnaTexts, entityTxt, proRef, negRef){

	var series;
	var pointsArray;

	if(typeof proPoints === 'boolean'){

		title = "Prominence of " + title;
		pointsArray = [points];
		series = [{color: 'black'}];
 		
	}else{

		title = "Sentiment towards: " + title;
		series = [
			 		{color: 'black'},
			 		{color: 'green'},
			 		{color: 'red'}
		 		];
		
		pointsArray = [points, proPoints, antiPoints];
		/*pointsArray = [points, proPoints, localProAvg, antiPoints, localAntiAvg];
		series = [
			 		{color: 'black'},
			 		{color: 'green'},
			 		{color: '#99FF99'},
			 		{color: 'red'},
			 		{color: '#FF6666'}
		 		];*/

	}

		  var plot3 = $.jqplot('sampleDiv', pointsArray, 
			{ 
			   	  animate:!$.jqplot.use_excanvas,		      		  					
				  title: {
							fontFamily: FONT_FAMILY,
							text: title,
							fontSize: TITLE_FONT_SIZE
						},
				    seriesDefaults: {
							renderer:$.jqplot.MekkoRenderer,
					        showMarker:true,
					        pointLabels: { show:false },
					        lineWidth: 1 
					      },
				    series: series,      
					legend: { 
								show:true,
								location: 'e',
								labels:['Entity prominence', 'Positive Sentiment', 'Negative Sentiment', 'Anti average', 'Pro average'],
								placement: 'outsideGrid',
								fontSize: 15},
					      			           		
					axes:{
			    	  axesDefaults: 
			    	  {	
						tickRenderer: $.jqplot.CanvasAxisTickRenderer ,	    	    
			    	    tickOptions: { 
			    	              formatString: '%d' 
			    	          } 
			    	  },
					xaxis:{
			    		renderer:$.jqplot.DateAxisRenderer,	
			    		tickRenderer:$.jqplot.CanvasAxisTickRenderer,	
						label: X_LABEL,
						tickOptions:{
							formatString:' %Y-%m-%e ',
							angle: ANGLE,
							fontSize: '7pt'							
							},	
						//tickInterval: '1 day',
						//ticks: xLabelPoints,	
						labelOptions:{
							fontFamily: FONT_FAMILY,
							fontSize: '15pt'
						  	}
						},
					yaxis:{	
					  tickRenderer:$.jqplot.CanvasAxisTickRenderer,					  
					  labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
					  label:Y_LABEL,
					  tickOptions: {
							formatString: "%#.1f%",
							fontSize: '10pt'
							  },
					  labelOptions: {
										fontFamily: FONT_FAMILY,
										fontSize: '15pt'
									},
					  min:0,
		              max:100
						}  						  				
						  
					},
					highlighter: {
				        show: true,
				        sizeAdjust: 7.5
				      },
				    cursor: {
				        show: false
				      }
			}
		  );

	var start = xLabelPoints[0];
	var end = xLabelPoints[xLabelPoints.length-1];
	var fromToDate = start + " -- " + end;

	if(typeof proPoints === 'boolean'){
		showInformation(fromToDate, allAnaTexts, entityTxt, proPoints);
	}else{
		showInformation(fromToDate, allAnaTexts, entityTxt, proRef, negRef);
	}
	
	addDownloadBtn("#btn");  
}

function makeChartAvg(title, points, pro, localPro, anti, localAnti, allAnaTexts, entityTxt, proRef, negRef, fromToDate ){

	var series;
	var pointsArray;

	if(typeof pro === 'boolean'){
		title = "Prominence of " + title;
		pointsArray = [points];
		series = [{color: 'black'}];
 		
	}else{

		title = "Sentiment towards: " + title;
		series = [
		 		{color: 'black'},
		 		{color: 'green'},
		 		{color: 'red'}
				];
		pointsArray = [points, pro, anti];
		/*series = [
					{color: 'red'},
					{color: 'green'},
			 		{color: 'black'},
					];
		pointsArray = [anti, pro, points];
		title = "Sentiment towards: " + title;
		/*console.log(pro);
		series = [
		 		{color: 'black'},
		 		{color: 'green'},
		 		{color: '#99FF99'},
		 		{color: 'red'},
		 		{color: '#FF6666'}
				];
		pointsArray = [points, pro, localPro, anti, localAnti];*/

	}

	var plot3 = $.jqplot('sampleDiv', pointsArray, {
	  	animate:!$.jqplot.use_excanvas,  
		title: {
					fontFamily: FONT_FAMILY,
					text: title,
					fontSize: TITLE_FONT_SIZE
			},
        seriesDefaults: {
				renderer:$.jqplot.MekkoRenderer,
		        showMarker:true,
		        pointLabels: { show:false } 
		      },
		series: series,
		legend: { 
					show:true,
					location: 'e',
					labels:['Entity prominence', 'Positive Sentiment', 'Negative Sentiment'],
					placement: 'outsideGrid',
					fontSize: 15}, 		      
        axesDefaults: {
            tickRenderer: $.jqplot.CanvasAxisTickRenderer ,
            tickOptions: {
              fontSize: '10pt'
            }
        },
        axes: {          
          xaxis: {
          	tickRenderer: $.jqplot.CanvasAxisTickRenderer,
            renderer: $.jqplot.CategoryAxisRenderer,
            label: X_LABEL,
            labelOptions: {
				fontFamily: FONT_FAMILY,
				fontSize: '15pt'
			},
			tickOptions: {
				angle: ANGLE	
			}
          },
			yaxis:{	
			  tickRenderer:$.jqplot.CanvasAxisTickRenderer,					  
			  labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
			  label:Y_LABEL,
			  tickOptions: {
					  formatString: "%#.0f%",
					  fontSize: '10pt'
					  },
			  labelOptions: {
								fontFamily: FONT_FAMILY,
								fontSize: '15pt'
							},
			  min:0,
			  max:100
				}  
        },
		highlighter: {
	        show: true,
	        sizeAdjust: 10,
	        tooltipLocation: 'n',
	        tooltipAxes: 'y',
	        tooltipFormatString: '<b><i><span >%.0f%</span></i></b>',
	        useAxesFormatters: false
	      },
	      cursor: {
	        show: false
	      }
      });
    //window.alert(proRef);
    if(typeof pro === 'boolean'){
    	showInformation(fromToDate, allAnaTexts, entityTxt, pro, negRef);
    }else{
		showInformation(fromToDate, allAnaTexts, entityTxt, proRef, negRef);
    }
	addDownloadBtn("#btn"); 
}