$(document).ready(function(){

	dc.plot_tip = {
		speed: 200
	};
	(function(plot_tip){
		plot_tip.kill = function(tip, cb){
			if(typeof(tip) == 'undefined'){
				$('.plot_tip').each(function(){
					plot_tip.kill($(this));
				});
			}else if(tip.hasClass('plot_tip')){
				tip.stop(true);
				tip.fadeOut(plot_tip.speed, function(){
					tip.remove();
					if(cb) cb();
				});
			}else{
				if(cb) cb();
			}
		};
		plot_tip.make = function(cb){
			plot_tip.kill($('#plot_tip'), function(){
				cb($('<span id="plot_tip"></span>').addClass('plot_tip').hide(0));
			});
		};
		plot_tip.init = function(graph){
			graph.hash = '';
			graph.drawTip = function(x, y, html){
				plot_tip.make(function(tip){
					tip.css({
						left: x + 'px',
						top: y + 'px'
					}).html(html).appendTo(document.body);
					tip.stop(true);
					tip.fadeIn(plot_tip.speed);
					graph.mouseleave(function(){
						graph.unbind('mouseleave');
						plot_tip.kill(tip, function(){
							graph.hash = '';
						});
					});
				});
			};
			graph.tipHover = function(event, pos, item){
				if(!item) return;
				hash = dump(item.datapoint);
				if(graph.hash == hash) return;
				graph.hash = hash;
				// count
				var item_date = new Date(item.datapoint[0]);
				var hours = item_date.getUTCHours();
				var minutes = item_date.getUTCMinutes();
				if(minutes < 10) minutes = '0' + minutes;
				var item_value = item.datapoint[1];
				// draw tip
				graph.drawTip(3 + item.pageX, 2 + item.pageY, '<span class="date">' + hours + ':' + minutes + '</span><span class="value" style="color: ' + item.series.color + ';">' + item_value + '</span>');
			};
			graph.bindTipHover = function(){
				graph.bind('plothover', graph.tipHover);
			}
			graph.bindTipHover();
		}
	})(dc.plot_tip);

	dc.initGraph = function(container, params){
		if(!container.length) return;
		dc.plot_tip.init($('.indices_graph', container));
		$('.indices_filter select', container).change(function(){
			dc.loadGraphTo(container, params);
		});
		dc.loadGraphTo(container, params);
	};

	dc.loadGraphTo = function(container, params){
		var getIssueCell = function(key){
			return $('.index_stat_' + key, container);
		}
		var setIssueCellValue = function(key, value){
			getIssueCell(key).html(value);
		}
		var setIssueCellSignColor = function(key){
			var value = getIssueCell(key).html();
			if(value == 'undefined' || value == 'null' || value == ''){
				getIssueCell(key)
					.removeClass('proc-plus')
					.removeClass('proc-minus')
					.html('&mdash;')
					;
			}else{
				var is_positive = (value >= 0);
				getIssueCell(key)
					.html((is_positive ? '+' : '') + value + ' %')
					.addClass(is_positive ? 'proc-plus' : 'proc-minus')
					.removeClass(is_positive ? 'proc-minus' : 'proc-plus')
					;
			}
		}
		var getIssueTitle = function(code, name){
			return (name == code) ? code : (name + ' (' + code + ')');
		}
		var getFilterValue = function(key){
			return $('.indices_filter *[name="' + key + '"]', container).val();
		}
		var showLoader = function(){
			$('.indices_filter .dc_loader', container).fadeIn();
		}
		var hideLoader = function(){
			$('.indices_filter .dc_loader', container).fadeOut();
		}
		dc.plot_tip.kill();
		showLoader();
		dc.ajax.post('indices_load', {
			issue: getFilterValue('issue'),
			mode: getFilterValue('mode')
		}, function(resp){
			hideLoader();
			setIssueCellValue('name',			getIssueTitle(resp.status.code, resp.status.name_ru));
			setIssueCellValue('moment',			resp.status.moment);
			setIssueCellValue('value',			resp.status.value || '&mdash;');
			setIssueCellValue('open_value',		resp.status.open_value || '&mdash;');
			setIssueCellValue('open_change',	resp.status.open_change);
			setIssueCellValue('close_change',	resp.status.close_change);
			setIssueCellSignColor('open_change');
			setIssueCellSignColor('close_change');
			var graph_setup = eval('[' + resp.graph + ']');
			if(graph_setup[0].data){
				dc.drawGraph(container, graph_setup, params);
			}else{
				dc.dongleGraph(container);
			}
		}, function(resp){
			hideLoader();
			alert(resp.error);
		});
	}

	dc.drawGraph = function(container, data, params){
		$.plot($('.indices_graph', container), data, {
			xaxis: {
				mode: 'time'
			},
			series: {
				points: { show: false },
				lines: { show: true }
			},
			colors: [
				params.color
			],
			grid: {
				hoverable: true
			}
		});
	}

	dc.dongleGraph = function(container, params){
		$('.indices_graph', container).html('<span>К сожалению, свежие данные ещё не поступили. Посмотрите пока <a href="/indices/">графики за более длительный период</a>.</span>');
	};
	
});