﻿// JScript File

var chart = new Array();
//clientID = ElementID
//dataPath = Path to the CSV
//schemaID = ColorSchema identifier could be int or name
//width = width of the complete chart
//height = hieght of the complete chart
function setupPieChart(clientID, dataPath, schemaID, width, height) {
		if(chart[0] == null)
		{
			chart[0] = new Object();
		}
		//Default Values
		var enableLabels = true;
		var enableLegend = false;
		var size = '75%';
		
		//We are on a small Pie use space we have
		if(width != 0 && width < 500){
			enableLabels = false;
			enableLegend = true;
			size='100%';
		}
		
		//If we get no width or height that back to default Value and use dynamic rendering of the Chart 
		if(width == 0)
		{
			width = null;
		}
		if(height == 0)
		{
			height = null;
		}
		
		//Options for the Pie Chart
   var options = {
      chart: {
         renderTo: clientID,//ElementID in which we Render
         plotBackgroundColor: null,
         plotBorderWidth: null,
         plotShadow: true,
         //Chart-Type
         defaultSeriesType: 'pie',
         width: width,
         height: height
      },
      legend: {
				borderWidth: 0,//no border on legend
				lineHeight: 16,//set lineHeight only for calculate chart Height with legend
				layout: "vertical"//Could only display line breaks on vertical
      },
      title: {
         text: null
      },
      subtitle: {
         text: null
      },
      tooltip: {
      enabled: false
      },
      plotOptions: {
         pie: {//pie options
            size: size,
						innerSize: '10%',//inner circle
            allowPointSelect: true,
            cursor: 'pointer',
            dataLabels: {
							distance:50,//distance of Labels to the chart
							enabled: enableLabels,
							formatter: function() {//format function
									return this.point.name +': '+ this.y +'%';
									 }
            },
            showInLegend: enableLegend//Add to value legend (Only if legend is enabled)
         }
      },
      credits: {
         enabled: false//could display here a copyright
      },
      series: []//empty series because is set by get function
   };
   //Read CSV (Name,Value,Color\n)
   $.get(dataPath, function(data) {
      // Split the lines
      var lines = data.split('\n');
      //Create series data array
      var series = {
         data: []
      };
      
      // Iterate over the lines and add categories or series
      var i = 0;//counts current position for Color
      $.each(lines, function(lineNo,line) {
         var items = line.split(',');
         
         var color = items[2];//get Color from CSV
         if(color == ""){//No color in CSV
						color = getDefaultColorBySchemaID(schemaID,i);//Read it from Color Array
         }
         series.data.push({//push Item into data Array
            type:'pie',
            name: items[0],
            y:parseFloat(items[1]),
            color: color
         });
         i++;
      });
      if(enableLegend){
				options.chart.height = (height + (i*options.legend.lineHeight));//We need a higher Area if we enable Legend
      }
      
      options.series.push(series);//push series into chart options
      // Create the chart
    chart[0][clientID] = new Highcharts.Chart(options);//create Chart with chart options
   });
 }
 
//clientID = ElementID
//dataPath = Path to the CSV
function setupColumnChart(clientID, dataPath, schemaID) {
		if(chart[1] == null)
		{
			chart[1] = new Object();
		}
   var options = {//Chart options
      chart: {
         renderTo: clientID,//ElementID in which we Render
         defaultSeriesType: 'column',//Set chart type
         marginBottom:110//need margin Bottom so we could show legend at the bottom of the Chart
      },
      title: {
         text: null
      },
      subtitle: {
         text: null
      },
      xAxis: {
         categories: [
         ],
				 labels: {
            rotation: -90,//rotate label by 90°
            align: 'right'
            }
      },
      yAxis: {
         min: 0,
         title: {
            text: null//here we could set a title of the yAxis
         }
      },

      legend: {//positioning of legend
         align: 'left',
         verticalAlign: 'bottom',//possible Values top, middle, bottom
         floating: true// so we are free to set legend where we want could also be in the chart
      },
      tooltip: {
				//Default at tooltip perhaps we have to change this later
         formatter: function() {
            return ''+
              this.y +' Mrd. EUR';
         }
      },
      plotOptions: {
         column: {
            pointPadding: 0,//no paading between columns
            borderWidth: 0
         }
      },
      credits: {
         enabled: false//could display here a copyright 
      },
     series: []//empty series because is set by get function
   };
   
 $.get(dataPath, function(data) {
    // Split the lines
    var lines = data.split('\n');
    
    // Iterate over the lines and add categories or series
    var i = 0;//counts current position for Color
    $.each(lines, function(lineNo, line) {
        var items = line.split(',');
        // header line containes categories
        if (lineNo == 0) {
            $.each(items, function(itemNo, item) {
            if(itemNo > 0) options.xAxis.categories.push(item);//Add categorie to xAxis (for example timeline x-Values)
            });
        }
        
        // the rest of the lines contain data with their name in the first position
        else {
            var series = {
                data: []
            };
            $.each(items, function(itemNo, item) {
                if (itemNo == 0) {
                //do some translations for our Series
									if (item == 'TotalMarketVolume'){
									series.name = 'Schätzung Gesamtmarkt';
									}
									else if(item == 'SelectedIssuerVolume'){
									series.name = 'Open Interest für 16 Emittenten';
									}
								//fallback on the Name from the CSV
									else {
									series.name = item;
									}
									series.color = getDefaultColorBySchemaID(schemaID,i);//Get Color from Schema or use default
									i++;
                } else {
                //Parse Values to float so they are correct shown on Chart
                    series.data.push(parseFloat(item));
                }
            });
            //push series into Options
            options.series.push(series);	
        }
        
    });

//create Charts with Options
   chart[1][clientID] = new Highcharts.Chart(options);
   });
 }
 
 var chartDefColors = new Array();
 //Get Color Schema for Chart
 function getDefaultColorBySchemaID(schemaID, position)
 {
 //declare array with 2 dimensions so we have a string index
	if(chartDefColors[0] == null){
			chartDefColors[0]= new Array();
			//Declare Color schemas 
			chartDefColors[0]['timeline_volume_chart_settings'] = '#4572A7,#AEAEB0';
			chartDefColors[0]['settings-trend-des-monats'] = '#3e5280,#5971b3,#8797cc,#b6bdda,#1e3469';
			chartDefColors[0]['trend_of_month_settings'] = '#3e5280,#5971b3,#8797cc,#b6bdda,#1e3469';
	}
	//read selected schema
	var colorString = chartDefColors[0][schemaID];
	//Choose current Color
	if(colorString != null || colorString == ""){
		var color = colorString.split(',')[position];
		if(color == null){
			return "";
		}
		else{
			return color;
		}
	}
 }
