(function( $ ) {
	$.fn.groupChart = function() {
		var $block = $(this),
			$chart = $block.find('.ticker_group_chart'),
			$legend = $block.find('.ticker_group_legend tr'),

			limit = 3,
			loaded = false,
			colors = ['#558fcc', '#c4057e', '#ffc452'],
			group = $block.data('group');


		var init = function() {
			// on load initialisation
			var border = $(window).scrollTop() + $(window).height();
			if (!loaded && border >= $block.offset().top){
				loaded = true;
				load();
				bind();
			}
			// on scroll (lazy) initialisation
			$(window).bind('scroll touchstart touchend', function() {
				var border = $(window).scrollTop() + $(window).height();
				if (!loaded && border >= $block.offset().top){
					loaded = true;
					load();
					bind();
				}
			});
		},
		load = function() {
			// first draw
			for (var i = 0; i < limit; i++) {
				$block.find('input[type="checkbox"]:eq(' + i + ')').attr('checked', 'checked');
			}
			var names = getNames();
			drawChart(names);
			drawLegend(names);
		},
		bind = function() {
			// selecte active charts
			$block.find('input[type="checkbox"]').click(function(){
				if ($block.find('input[type="checkbox"]:checked').size() > limit) {
					return false;
				}

				var names = getNames();
				drawChart(names);
				drawLegend(names)
			});

			// change type
			$legend.on('click', 'a', function() {
				$(this).closest('td').toggleClass('active');

				var names = getNames();
				drawChart(names);

				return false;
			});
		},
		drawChart = function(names) {
			$chart.empty();
			if (!names || names.length <= 0) {
				return false;
			}

			$chart.hover(function() {
			}, function() {
				_overCallback(null);
			});

			var DataTable = new google.visualization.DataTable();
			DataTable.addColumn({type:'datetime', role:'domain'});

			var date = '',
				chart_data = {},
				legend_data = {},
				n = 1,
				series = {},
				annotation = {},
				vAxis = {};

			for (var i = 0; i < names.length; i++) {
				var name = names[i].ticker + '.' + names[i].exchange,
					title = name.split('.')[0],
					json = names[i].data,
					tmp = [];

				if (json == undefined) {
					continue;
				}

				DataTable.addColumn({type:'number', role:'data', label: title});
				vAxis[i] = {
					maxValue: 0,
					minValue: 0
				};
				series[i] = { targetAxisIndex: i };
				if (names[i].type != undefined) {
					series[i].type = names[i].type;
				}
				for (var j = 0; j < json.length; j++) {
					var date_key = json[j].dt,
						date_key2 = json[j].dt.split(' ')[0];

					if (chart_data[date_key] == undefined) {
						tmp = date_key.split(' ')[0].split('-');
						tmp2 = date_key.split(' ')[1].split(':');
						chart_data[date_key] = {0: new Date(tmp[0], tmp[1]-1, tmp[2], tmp2[0], tmp2[1])};
						legend_data[date_key] = {0: new Date(tmp[0], tmp[1]-1, tmp[2], tmp2[0], tmp2[1])};
					}

					chart_data[date_key][n] = parseFloat(json[j].c);
					legend_data[date_key][n] = parseFloat(json[j].dp)

					if (vAxis[i].maxValue < json[j].c) { vAxis[i].maxValue = json[j].c; }
					if (vAxis[i].minValue > json[j].c) { vAxis[i].minValue = json[j].c; }

					for (var k = 1; k <= n; k++) {
						if (chart_data[date_key][k] == undefined) {
							chart_data[date_key][k] = null;
							legend_data[date_key][k] = null;
						}
					}
				}

				n++;
			}
			chart_data = _prepareData(chart_data, n);
			legend_data = _prepareData(legend_data, n);

			if (!chart_data || chart_data.length <= 1) {
				return false;
			}

			$block.data('legend_data', legend_data);

			DataTable.addRows(chart_data);

			// column 0 (date) format
			var datetime_format = new google.visualization.DateFormat({pattern: 'dd.MM.yyyy HH:mm'});
			datetime_format.format(DataTable, 0);

			// column 1...n (number) format
			var number_format = new google.visualization.NumberFormat({
				decimalSymbol:',',
				fractionDigits:2,
				groupingSymbol:'',
				negativeParens:false,
				prefix:'',
				suffix:''
			});
			for (var i = 0; i < names.length; i++) {
				number_format.format(DataTable, i + 1);
			}

			var chart = new google.visualization.LineChart($chart[0]); // Create and draw the visualization.

			vAxis.baselineColor = '#c6c6c6';
			vAxis.gridlines = {
				color: '#ebebeb',
				count: 7
			};
			vAxis.slantedText = false;
			vAxis.textPosition = 'none';

			chart.draw(DataTable, {
				annotation : annotation,
				width: 466,
				height: 235,
				areaOpacity: .1,
				colors: colors,
				tooltip: { /* trigger: 'none', *//*isHtml: true*/ },
				interpolateNulls: true,
				focusTarget: 'category',
				legend: { position: 'none' },
				hAxis: { // вертикальные
					baselineColor: 'none',
					slantedText: false,
					gridlines: { color: 'none' },
					textStyle: {
						color: '#6d6d6d',
						fontSize: '9px'
					}
				},
				vAxis : vAxis,
				series : series,
				chartArea: {
					top: 10,
					left: 0,
					width: 466,
					height: 200,
				}
			});

			google.visualization.events.addListener(chart, 'onmouseover', _overCallback);

			$block.show();
		},
		drawLegend = function(names) {
			$legend.empty();

			if (!names || names.length <= 0) {
				return false;
			}

			for (var i = 0; i < names.length; i++) {
				var name = names[i].ticker + '.' + names[i].exchange,
					title = names[i].view_name;

				$legend.append('<td data-name="' + name + '"><div style="background-color:' + colors[i] + '"></div><a href="#">' + title + '</a><span></span></td>');
			}
		},
		getNames = function() {
			var names = [];
			$block.find('input[type="checkbox"]:checked').each(function() {
				names.push({
					ticker: $(this).closest('tr').data('ticker'),
					exchange: $(this).closest('tr').data('exchange'),
					type: $('.ticker_group_legend td[data-name="' + $(this).closest('tr').data('ticker') + '.' + $(this).closest('tr').data('exchange') + '"]').hasClass('active') ? 'area' : 'line',
					title: $(this).closest('tr').data('title'),
					view_name: $(this).closest('tr').data('view-name'),
					data: $(this).closest('tr').data('data')
				});
			});

			return names;
		},
		_overCallback = function(pos) {
			var legend_data = $block.data('legend_data');

			var cl = '',
				sign = '',
				row, len, k, i;

			$legend.find('td span').removeClass('up').removeClass('down').text('');
			if (pos !== null && pos.row != undefined) {
				row = legend_data[pos.row];
				len = row.length - 1;
				for (i = 0; i < len; i++) {
					k = i + 1;
					if (row[k]) {
						if (row[k] > 0) { cl = 'up'; sign = '+'; }
						if (row[k] < 0) { cl = 'down'; sign = ''; }

						$legend.find('td:eq(' + i + ') span').addClass(cl).text(sign + row[k].toFixed(2).replace('.', ',') + '%');
					}
				}
			}
		},
		_prepareData = function(arr, cols){
			// Setup Arrays
			var sortedKeys = [],
				sortedObj = [];

			// Separate keys and sort them
			for (var i in arr){
				sortedKeys.push(i);
			}
			sortedKeys.sort();

			// Reconstruct sorted obj based on keys
			for (var i in sortedKeys){
				tmp = [];
				for (var j = 0;j < cols;j++) {
					if (arr[sortedKeys[i]][j] != undefined) {
						tmp.push(arr[sortedKeys[i]][j]);
					} else {
						tmp.push(null);
					}
				}
				sortedObj.push(tmp);
			}
			return sortedObj;
		}

		init();
	};
})( jQuery );
