/**
 * class Stock
 *
 * Contains all the necessary elements to manage stock data.
 *
 * Requires helpers.js, class_Stats.js, class_StatChart.js, ajax_getPrices.php
 *
 * @param sym the stock symbol
 * @param paper a reference to the paper that will be the rendering space for data
 *
 * @author Justen Robertson <justen@justenrobertson.com>
 * @link http://www.justenrobertson.com
 * @version 0.4.1a 6/8/2009
 * @license Proprietary (all rights reserved)
 * @copyright 2009 Justen Robertson
 */
function Stock(sym, paper) {
	this.sym = sym;
	this.paper = paper;
	this.liveData = {};
	this.liveChart = false;
	this.chart = new StatsChart(paper);
	this.cmdQueue = [];
	this.sInterval = 0;
	this.dateBase = 0;
	this.proccing = 0;
	this.waiting = 1;
	this.sLow = new Statistic();
	this.sHigh = new Statistic();
	this.sClose = new Statistic();
	this.sLow = new Statistic();
	this.sVol = new Statistic();
	this.sTime = new Statistic();
	this.lClose = new Statistic();
	this.lTime = new Statistic();




	this.fillData = function(data) {
		this.data = data;
	};




	this.buildData = function() {
		$('#symTabs').append("<li class='stockSymbol' id='"+this.sym+"_tab'><a href='#"+this.sym+"' style='color:"+this.chart.color+";'>"+this.sym+"</a></li>");
		$('#stockSymbols').append("\
		<div id='"+this.sym+"' class='stockBlock' style=''>\n\
		<div class='hStockLiveChart'>\n\
		</div>\n\
		<div class='hStockData'></div>\n\
		<div class='controls'><h4>Controls</h4>\n\
		<span class='ui-state-default ui-corner-all stocker-button'><input type='text' class='colorPicker' value='"+this.chart.color+"' /></span>\n\
		<a href='#' class='ui-state-default ui-corner-all stocker-button toggleVWAP'><span class='ui-icon ui-icon-plusthick'>+</span>VWAP</a>\n\
		<a href='#' class='ui-state-default ui-corner-all stocker-button toggleHoriz'><span class='ui-icon ui-icon-plusthick'>+</span>Lines</a>\n\
		</div>\n\
		<div class='stockDataInfo'>\n\
		</div>\n\
		</div>"
		);
		var me = this;


		$("#"+this.sym+" .stocker-button").hover(
			function(){
				$(this).addClass("ui-state-hover");
			},
			function(){
				$(this).removeClass("ui-state-hover");
			}
		);
		
		$("#"+this.sym+" .colorPicker").colorInput({
			cells:5,
			cellSize:15,
			colorSelected:function(){
				var sym = me.sym;
				var color = this.value;
				$('#'+sym+' .symbol').css({color:color});
				$('#'+sym+'_tab a').css({color:color});
				me.chart.setColor(color);
				me.liveChart.setColor(color);
			},
			hueWidth:15
		});

		$("#"+this.sym+"_tab a").bind('click', function(e) {e.preventDefault(); me.chart.toFront();});
		$("#"+this.sym+" .toggleVWAP").live('click', function(e){e.preventDefault(); me.chart.toggleLines('vWAP');});
		$("#"+this.sym+" .toggleHoriz").live('click', function(e){e.preventDefault(); me.chart.toggleLines('horizontal');});

		var required = ['d', 'c', 'v', 'l', 'h'];
		this.getData(required);
		me.liveUpdate();
		me.systemUpdateCallback();
	};




	this.buildLiveChart = function() {
		if(this.liveChart === false) {
			var field = $("#"+this.sym+" div.hStockLiveChart")[0];
			var paper = Raphael(field, $('#stockSymbols').width()*.94, $(field).height());
			this.liveChart = new StatsChart(paper);
			var i = 0;
			for (i=1;i<101;i++) {this.lTime.add(i);}
			this.lClose.fill({amt:100, dir:'left', value:this.lClose.stats[0]});
		}
		this.liveChart.setData({color:this.chart.color, xfac:this.lTime, yfac:this.lClose});
		this.liveChart.plotHorizontal();
	}




	this.getData = function(required) {
		var me = this;
		for (var i in required) {
			if(typeof(required[i]) == 'string') {
				new $.get(
					'ajax_getPrices.php?sym='+me.sym+'&opts='+required[i],
					function(res) {
						var data = eval("("+res+")");
						me.queueUpdate(data);
					}
				);
			}
		}
	};




	this.queueUpdate = function(data) {
		var cmd = {
			stock:this,
			data:data,
			execute: function() {
				this.stock.updateData(this.data);
				this.stock.proc();
			}
		}
		this.queue(cmd);
	}




	this.queue = function(cmd) {
		this.cmdQueue.push(cmd);
		if(!this.proccing) this.proc();
		return this; // so we can chain them
	}




	this.proc = function() {
		var cmd = this.cmdQueue.shift();
		if(cmd) cmd.execute();
		if(this.cmdQueue.count()) this.proccing = 1;
		else this.proccing = 0;
		return this;
	}




	this.updateData = function(data) {
		var time = (this.begin)?new Date(this.begin*1000).toUTCString():"...";
		$("#"+this.sym+">.stockDataInfo").html("\n\
			<span>Data Points: "+data.dataSet.length+"</span>\n\
			<span>Start Date: "+time+"</span>\n\
			<span>Interval: "+Math.round(data.i*100/60)/100+" Minutes</span>\n\
		");
		this.setStats(data);
		var me = this;
		for (var i in data.col) {
			switch(data.col[i]) {
				case 'low':
				break;
				case 'high':
				break;
				case 'close':
					me.chart.setData({yfac:me.sClose});
					var subs = me.sClose.subset(-Math.round(data.i/4));
					subs.interpolate(100);
					this.lClose = subs;
				break;
				case 'date':
					me.chart.setData({xfac:me.sTime});
				break;
				case 'volume':
					me.chart.setData({sfac:me.sVol});
				break;
			}
		}
		if(this.sVol.count() && this.sTime.count() && this.sClose.count()) {
			me.chart.plotHorizontal();
			me.chart.plotVWAP(this.sVol, this.sClose);
		}
	}




	this.setStats = function(data) {
		if(data.i) this.sInterval = data.i;
		if(data.begin) this.begin = data.begin;
		var me = this;

		data.dataSet.each(function(e) {
			for(var i in data.col) {
				switch(data.col[i]) {
					case "low":
						me.sLow.add(e[i]);
					break;
					case "high":
						me.sHigh.add(e[i]);
					break;
					case "volume":
						me.sVol.add(e[i]);
					break;
					case "close":
						me.sClose.add(e[i]);
					break;
					case "date":
						if(typeof(e[i]) == 'string') e[i].indexOf('a')===0? me.sTime.add(0):me.sTime.add(e[i]);
						else me.sTime.add(e[i]);
					break;
				}
			}
		});
	}




	this.systemUpdateCallback = function() {
		return false;
	};




	this.liveUpdate = function() {
		var me = this;
		new $.get(
			'ajax_getLiveData.php?sym='+this.sym,
			function(r) {
				me.liveData = eval('('+r+')');
				me.liveUpdateCallback();
			}
		);
	};




	this.liveUpdateCallback = function() {
		$("#"+this.sym+">.hStockData").html("\n\
		<h3><span class='symbol' style='color:"+this.chart.color+"'>"+this.liveData.t+"</span>\n\
		:<span class='index'>"+this.liveData.e+"</span></h3>\n\
		<div class='currentData'>\n\
		<h4>Daytime</h4>\n\
		<span class='hStockLabel'>Price</span><span class='index'>"+this.liveData.l_cur+"</span>\n\
		<span class='hStockLabel'>Time</span><span class='ltt'>"+this.liveData.lt+"</span>\n\
		<span class='hStockLabel'>Change</span><span class='c'>"+this.liveData.c+"<span class='cp'>("+this.liveData.cp+"%)</span></span>\n\
		</div>\n\
		<div class='afterHours'><h4>After Hours</h4>\n\
		<span class='hStockLabel'>Price</span><span class='el_cur'>"+(this.liveData.el_cur?this.liveData.el_cur:'unavailable')+"</span></span>\n\
		<span class='hStockLabel'>Time</span><span class='elt'>"+(this.liveData.elt?this.liveData.elt:'unavailable')+"</span></span>\n\
		<span class='hStockLabel'>Change</span><span class='ec'>"+(this.liveData.ec?this.liveData.ec+"<span class='ecp'>("+this.liveData.ecp+"%)</span>":'unavailable')+"</span>\n\
		</div>");
		// now start looping, whee
		var me = this;
		if (this.lClose) {
			this.lClose.slide(this.liveData.el_cur?this.liveData.el_cur:this.liveData.l_cur);
			this.buildLiveChart();
			this.liveChart.toggleLines(false, 1);
		}
		setTimeout(function() {me.liveUpdate()}, 15000);
	};




	this.liveChartUpdate = function() {

	}




	this.getNasdaqData = function() {
		
	}




	this.toggleLines = function() {
		this.chart.toggleLines('horizontal');
		this.chart.toggleLines('vWAP', 0);
	}
}