﻿/*
scChart object definition ;-)

scChart.divName // string
scChart.snapshotID // int
scChart.chart // ejsChart object
scChart.series // object
scChart.snapshot // snapshot object
scChart.digits // force decimal digits
scChart.mode //default mode to display, string "a" or "r"
scChart.pairName //
scChart.pairID //
scChart.eventID //
scChart.intervalID //
scChart.column // int, 0, 1, 2, ... (column in grid)
series.candle;
series.line1;
series.line2;
series.mark;

snapshot.  // object ... TBD
*/

// part 1: one script per page - js functions and definitions only, no calls and execution at this point!
var charts = []; // most impotant - it will keep all data
var timeFrames = [1,5, 60, 30, 120];
var currentChartIndex = -1;

var xformater = [];
xformater[0] = new EJSC.DateFormatter({format_string: 'HH:NN:SS',useUTC: true}); // tick
xformater[1] = new EJSC.DateFormatter({format_string: 'HH:NN',useUTC: true}); // m1

var bottomFormatters = []; // for cursor_position

bottomFormatters[0] = null; // tick
bottomFormatters[1] = // M1
{
	format: function(value) {
		// Convert the value (integer) into a javascript date
		value = new Date(value);
		// Determine if the seconds portion of the value is greater or less than 30 and round the time up
		if (value.getSeconds() > 30) 
		{
			value.setMinutes(value.getMinutes() + 1);
		}
		// Return a string representation of the date:
		return (value.getHours() > 10 ? "" : "0") + value.getHours() + ":" + (value.getMinutes() > 10 ? "" : "0") + value.getMinutes();
	}
};
bottomFormatters[2] = // M15
{
	format: function(value) {
		value = new Date(value);
		value.setSeconds(value.getSeconds() + 7.5*60);
		return (value.getHours() > 10 ? "" : "0") + value.getHours() + ":" + (Math.floor(value.getMinutes()/15)*15 > 10 ? "" : "0") + Math.floor(value.getMinutes()/15)*15;
	}
};
bottomFormatters[3] = // M5
{
	format: function(value) {
		value = new Date(value);
		value.setSeconds(value.getSeconds() + 2.5*60);
		return (value.getHours() > 10 ? "" : "0") + value.getHours() + ":" + (Math.floor(value.getMinutes()/5)*5 > 10 ? "" : "0") + Math.floor(value.getMinutes()/5)*5;
	}
};
bottomFormatters[4] =  // M30
{
	format: function(value) {
		value = new Date(value);
		value.setSeconds(value.getSeconds() + 15*60);
		return (value.getHours() > 10 ? "" : "0") + value.getHours() + ":" + (Math.floor(value.getMinutes()/30)*30 > 10 ? "" : "0") + Math.floor(value.getMinutes()/30)*30;
	}
};



function SnapshotChartAddSeriesCandlestick()
{
	var o = charts[currentChartIndex];
	var c = o.chart;
	var s = o.series;
	var url = "/datafeed.ashx?t=snapshot&eventid=" + o.eventID + "&pairid=" + o.pairID + "&intervalid=" + o.intervalID + "&mode=" + o.mode;
	s.candle = new EJSC.CandlestickSeries(new EJSC.CSVFileDataHandler(url), 
		{intervalOffset : 0.7, title: o.pairName, y_axis: 'right', padding: { x_axis_min: 0, x_axis_max: 0, y_axis_min: 20, y_axis_max: 20 }}
	);
	c.addSeries(s.candle, false);
}

function SnapshotChartAddSeriesLine()
{
	var o = charts[currentChartIndex];
	var c = o.chart;
	var s = o.series;
	var url = "/datafeed.ashx?t=snapshot&eventid=" + o.eventID + "&pairid=" + o.pairID + "&intervalid=" + o.intervalID + "&line=ask&mode=" + o.mode;
	s.line1 = new EJSC.LineSeries(new EJSC.CSVFileDataHandler(url), {title: "Ask", y_axis: 'right', drawPoints : true, color: 'rgb(169,195,248)', padding: { x_axis_min: 0, x_axis_max: 0, y_axis_min: 20, y_axis_max: 20 }});
	c.addSeries(s.line1, false);
	
	url = "/datafeed.ashx?t=snapshot&eventid=" + o.eventID + "&pairid=" + o.pairID + "&intervalid=" + o.intervalID + "&line=bid&mode=" + o.mode;
	s.line2 = new EJSC.LineSeries(new EJSC.CSVFileDataHandler(url), {title: "Bid", y_axis: 'right', drawPoints : true, color: 'rgb(252,174,174)', padding: { x_axis_min: 0, x_axis_max: 0, y_axis_min: 20, y_axis_max: 20 }});
	c.addSeries(s.line2, false);
}
var dh;
function SnapshotChartAddMark()
{
/*
	var a = t.split("|");
	scatterDateTime = a[0];
	scatterValue = parseFloat(a[1]);

alert(t);
return;
*/
	var o = charts[currentChartIndex];
	//  o.scatterDateTime = scatterDateTime;
	//  o.scatterValue = scatterValue;
	var c = o.chart;
	var s = o.series;

	var url = "/datafeed.ashx?t=scatter&eventid=" + o.eventID + "&pairid=" + o.pairID + "&intervalid=" + o.intervalID + "&mode=" + o.mode;
	var dh = new EJSC.CSVFileDataHandler(url);
	s.mark = new EJSC.ScatterSeries(dh, {y_axis: 'right', title: o.scatterTooltip, color: 'rgb(135,206,235)', padding: { x_axis_min: 0, x_axis_max: 0, y_axis_min: 20, y_axis_max: 20 }});
	//if(s.mark.__points[0].y)
		c.addSeries(s.mark, false);
	
}

function SnapshotChartRemoveSeries()
{
	var o = charts[currentChartIndex];
	var c = o.chart;
	var s = o.series;
	if (s)
	{
		if (s.candle) {c.removeSeries(s.candle, false); s.candle = null; }
		if (s.line1) {c.removeSeries(s.line1, false); s.line1 = null; }
		if (s.line2) {c.removeSeries(s.line2, false); s.line2 = null; }
		if (s.mark) {c.removeSeries(s.mark, false); s.mark = null; }
		s = null;
	}
}



function CreateSnapshotChart(mySCChart)
{
	if(mySCChart.chart)
		return; // we already hawe chart created
	
	mySCChart.chart = new EJSC.Chart(mySCChart.divName, 
{
 title: mySCChart.pairName,
  proximity_snap: 5,
  show_messages: true, 
  allow_interactivity: true, 
  allow_mouse_wheel_zoom: false,
  building_message: "Building" ,
  drawing_message: "Drawing Spike Chart",
  show_legend: false, 

  axis_left: { visible: false },
  axis_bottom: {
  caption: "",
  crosshair: { show: true, color: 'rgb(212,212,212)' },
  cursor_position: { show: true, color: 'rgb(151,165,255)'},
  
       major_ticks: {
        color: 'rgb(0,0,255)',
        count: 5,
        offset: 5,
        opacity: 80,
        show: true,
        size: 5,
        thickness: 1 
       },

       minor_ticks: {
        color: 'rgb(200,200,200)',
        count: 10,
        offset: 0,
        opacity: 20,
        show: true,
        size: "100%",
        thickness: 1 
       },       
       size: 15
  },
  axis_right: {
  show: true,
  caption: "",
  crosshair: { show: true, color: 'rgb(212,212,212)' },
  cursor_position: { show: true, color: 'rgb(151,165,255)'},
      major_ticks: {
        color: 'rgb(0,0,255)',
        count: 10,
        offset: 5,
        opacity: 80,
        show: true,
        size: 5,
        thickness: 1 
       }
      }
  }

	);
	
	
//	mySCChart.chart.onBeforeDraw = function( chart ) { 
//		chart.setTitle("Drawing Chart ..."); 
//		alert("onBeforeDraw");
//	}; 
//	mySCChart.chart.onAfterDraw = function( chart ) { 
//		chart.setTitle("Finished Drawing");
//		alert("Finished Drawing");
//	}; 
	
	mySCChart.series = {};
}

function DisplaySnapshotChart (divName)
{
	var j = -1;
	for (var i=0; i< charts.length; i++)
		if (charts[i].divName == divName)
			{j=i; break;}
	if (j > -1)
	{
//		currentChartIndex = j;
//		var o = charts[currentChartIndex];
//		CreateSnapshotChart(o); // this will create only once
//		chart_redraw()
		DisplaySnapshotChartById (j);
	}
}
function DisplaySnapshotChartById (j)
{
	currentChartIndex = j;
	var o = charts[currentChartIndex];
	CreateSnapshotChart(o); // this will create only once
	chart_redraw();
}

function chart_redraw()
{
	var o = charts[currentChartIndex];
	
	var digits = 1 // relative with 1 digit
	if (o.mode.toUpperCase() != 'R')
		digits = o.pairName.toUpperCase().indexOf("JPY") >= 0 ? 3 : 5; 

	SnapshotChartRemoveSeries();
	
	o.chart.axis_right.formatter = new EJSC.NumberFormatter({forced_decimals: digits, variable_decimals: 0})
	o.chart.axis_bottom.formatter = xformater[o.intervalID == 1 ? 0 : 1];
	//o.chart.axis_bottom.cursor_position.formatter = bottomFormatters[o.intervalID-1];

	if (o.intervalID == 1)
	{
		SnapshotChartAddSeriesLine();
	}
	else
	{
		SnapshotChartAddSeriesCandlestick();
	}
	SnapshotChartAddMark();
	//Gaia.Control.callPageMethod('SnapshotScatterMark', [o.eventID, o.pairID, o.intervalID, 1, o.mode], SnapshotChartAddMark); // bring data for scater
	o.chart.setTitle (o.pairName);
	o.chart.redraw(true);

//	setTimeout("alert(" + timeFrames[o.intervalID-1] + ")",2000);
	//o.chart.axis_bottom.major_ticks.min_interval=(1000*60* timeFrames[o.intervalID-1]);
	//o.chart.axis_bottom.major_ticks.max_interval=(1000*60* timeFrames[o.intervalID-1]);

}
/*
function UpdateTime(ccc)
{
	
	alert(charts[currentChartIndex].intervalID);
}
*/

function AddChart(divName, eventID, pairID, intervalID, digits, mode, pairName, column, scatterTooltip)
{
	// scchart object initiation
	charts[charts.length] = {divName: divName, eventID: eventID, pairID: pairID, intervalID: intervalID, digits: digits, mode: mode, pairName: pairName, column: column, scatterTooltip: scatterTooltip};

	// display chart
	
//	Ext.onReady(function() {
///		DisplaySnapshotChart (divName);
//	});
	
	//initial setup
	gebi(divName + "_tab_" + intervalID).className = "selected";
	gebi(divName + "_mode_" + mode.toUpperCase()).checked = true;
}

function LoadNextCharts(maxRows)
{
	// find next not-yet-loaded charts (one pair) and load/create them
	var i=0;
	for (var n = 0; n < charts.length; n++)
	{
		if (!charts[n].chart)
		{
			DisplaySnapshotChartById (n);
			i++;
		}
		if (i/2 >= maxRows)
			return;
	}
}

//function DisplaySnapshotCharts(n0, n1, d)
//{
//	for (var n = 0; n <= n1; n++)
//		setTimeout(function(){ DisplaySnapshotChart (charts[n].divName); }, (n+1)*d);
//}
//// tabs

function interval_change_all(column, intervalID)
{
	for (var n = 0; n < charts.length; n++)
		if (charts[n].column == column)
		{
			gebi(charts[n].divName + "_tab_" + charts[n].intervalID).className = "display: none;"; // uncheck old
			charts[n].intervalID = intervalID;
			DisplaySnapshotChart (charts[n].divName); 
			gebi(charts[n].divName + "_tab_" + charts[n].intervalID).className = "selected"; // select new tab
		}
}

function pair_change_all(column, pairID, pairName)
{
	for (var n = 0; n < charts.length; n++)
		if (charts[n].column == column)
		{
			charts[n].pairID = pairID;
			charts[n].pairName = pairName;
			DisplaySnapshotChart (charts[n].divName); 
		}
}

function mode_change_all(column, mode)
{
	for (var n = 0; n < charts.length; n++)
		if (charts[n].column == column)
		{
			charts[n].mode = mode;
			DisplaySnapshotChart (charts[n].divName); 
			gebi(charts[n].divName + "_mode_" + mode.toUpperCase()).checked = true;
		}
}

function interval_change(divName, intervalID)
{
	var j = GetIndexByName(divName);
	charts[j].intervalID = intervalID;
	DisplaySnapshotChart (divName); 
}
function event_change(divName, eventID)
{
	var j = GetIndexByName(divName);
	charts[j].eventID = eventID;
	DisplaySnapshotChart (divName); 
}
/*
function snapshot_change(divName, snapshotID, intervalID, digits)
{
	var j = GetIndexByName(divName);
	charts[j].snapshotID = snapshotID;
	charts[j].intervalID = intervalID;
	charts[j].digits = digits;
	DisplaySnapshotChart (divName); 
}
*/
function mode_change(divName, mode)
{
	charts[GetIndexByName(divName)].mode = mode;
	DisplaySnapshotChart (divName); 
}

function GetIndexByName(name)
{
	var j = -1;
	for (var i=0; i< charts.length; i++)
		if (charts[i].divName == name)
			{j=i; break;}
	return j;
}
function change_class(obj) 
{
	// style
	var lis = obj.parentNode.parentNode.getElementsByTagName('li');
	for (i_tab = 0; i_tab < lis.length; i_tab++) 
	{
		lis[i_tab].childNodes[0].className="display: none;";
	}
	obj.className = "selected";
}

function gebi(s)
{
	return document.getElementById(s);
}

		//scc.snapshotID = parseInt(newSnapshotID);
		//scc.mode = mode;
		//scc.chart.setTitle ("snapshotID = " + scc.snapshotID);
		//Gaia.Control.callPageMethod('GetSnapshot', [scc.snapshotID, 1], AfterGetSnapshot); // 1 in this case is pairID, to do:
		
		//function AfterGetSnapshot(t)
		//{
		//	//t is string with pipe separated values: snapshotID, intervalid, forced decimals, ....
		//	var a = t.split("|");
		//	var o = charts[currentChartIndex];
		//	o.snapshotID = parseInt(a[0]);
		//	o.intervalID = parseInt(a[1]);
		//	o.digits = parseInt(a[2]);
		//	o.mode = a[3];

