// -----PricingLogic.js-----
function getRandom() {
	return new Date().getTime();
}

var PricingLogic = Class.create();
PricingLogic.prototype = {
	_id: null,
	_market: null,
	_url: null,
	_grid: null,
	_pager: null,
	_pusher: null,
	_getTicket: "getTicket",
	_isWorking: false,
	_codes: null,
	
	initialize: function(url, market, grid, pager, codes) {
		this._url = url;
		this._grid = $C(grid);
		this._pager = $C(pager);
		this._market = market;
		this._codes = codes;
	},
	
	start: function() {
		new Ajax.Request(
			this._url + "/getTicket?r=" + getRandom(),
			{method: 'GET', parameters: "", onComplete: this.onTicketArrived.bind(this)}
		);
	},
	
	onTicketArrived: function(response) {
		this._id = eval("("+ response.responseText + ")").Obj;
		this.setObserver();
	},
	
	setObserver: function(prefix) {
		var parm = "";
		parm += "ID=" + this._id;
		parm += "&Market=" + this._market;
		parm += "&PageSize=" + this._pager.PageSize;
		parm += "&Page=" + this._pager.CurrentPage;
		if (this._codes) parm += "&Codes=" + this._codes;
		if (prefix && prefix != "") parm += "&Prefix=" + prefix;
		
		new Ajax.Request(
			this._url + "/setObserver?r=" + getRandom() + "&" + parm,
			{method: 'GET', parameters: "", onComplete: this.onSetObserver.bind(this)}
		)
	},
	
	onSetObserver: function(response) {
		if (!this._isWorking) {
			this._isWorking = true;
			this._startPush();
		}
	},
	
	findRows: function(prefix) {
		if (!prefix || prefix == "") return [];

		var rows = [];		
		for (var i = 0; i < this._grid.Rows.length; i++) {
			var reg = new RegExp('^' + prefix.toLowerCase(), 'gm');
			var row = this._grid.Rows[i];
			if (reg.exec(row.Data.Code.toLowerCase())) rows.push(row);
		}
		return rows;
	},
	
	_startPush: function() {
		var parm = "?ID=" + this._id;
		var ieUrl = this._url + "/ie" + parm;
		var fxUrl = this._url + "/fx" + parm;
		this._pusher = new YTWeb.HttpPush(this._onPush.bind(this), ieUrl, fxUrl);
		this._pusher.send();
	},
	
	_onPush: function(data) {
		if (data.Type == "Restart") {
			this._pusher.send();
		}
		
		if (data.Type == "Pager") {
			this._pager.PageSize = data.Obj.PageSize;
			this._pager.TotalPages = data.Obj.Total;
			this._pager.CurrentPage = data.Obj.CurrentPage;
			this._pager.display();

			for (var i = 0; i < data.Obj.Items.length; i++) {
				this._processData(data.Obj.Items[i]);
			}
			this._grid.bindData(data.Obj.Items);
		}
		if (data.Type == "Symbol") {
			this._processData(data.Obj);
			this._grid.refresh(data.Obj, true);
		}
	},
	
	_processData: function(dataItem) {
		try {
			if (dataItem["Price"] != 0) {
				dataItem["Fluctuation"] = dataItem["Price"] - dataItem["Close"];
				dataItem["FluctuationRate"] = dataItem["Fluctuation"] / dataItem["Close"] * 100;
				if (dataItem["Close"] == 0) dataItem["FluctuationRate"] = 0;
				if (isNaN(dataItem["FluctuationRate"])) dataItem["FluctuationRate"] = 0;
			} else {
				dataItem["Fluctuation"] = 0;
				dataItem["FluctuationRate"] = 0;
			}
		} catch (e) {
			dataItem["FluctuationRate"] = 0;			
		}
	},
	
	checkGrid: function() {
		var grid = this._grid;
		for (var i = 0; i < grid.Rows.length; i++) {
			var row = grid.Rows[i];
			var tSpan = (new Date()).getTime() - row.LastUpdate.getTime();

		    if (tSpan > 3000) row.bindData(row.Data);
		}
	},
	
	quit: function() {
		this._pusher.abort();
	}
}

// -----Chart.js-----
var Chart = Class.create();
YTWeb.Controls.Reg("Chart", Chart);

Chart.prototype = {
	_urlStr: "http://chart.baring.cn:81/skychart/{0}/{2}/{3}/{4}{5}{6}/{1}.png",
	_blank: null,
	_defaultCode: null,
	_width: 0,
	_height: 0,
	_img: null,
	_select: null,
	_kline : null,
	_tline : null,
	_dline : null,
	_currentCode: null,

	initialize: function(e) {
		YTWeb.InitItem.bind(this)(e);
		
		this._defaultCode = $ATTR(e, "DefaultCode");
		
		var height = parseInt($ATTR(e, "Height"));
		var width = parseInt($ATTR(e, "Width"));
		
		this._height = !isNaN(height) ? height : 200;
		this._width = !isNaN(width) ? width : 200;
		
		var urlStr = $ATTR(e, "Url");
		if (urlStr) this._urlStr = urlStr;
		
		this._blank = $ATTR(e, "BlankImg");
		
		this._createSelect();
		this._createImg();
		
		if (this._defaultCode) this.show(this._defaultCode);
	},
	
	show: function(code) {
		if (!code) code = this._currentCode;
		this._img.src = code ? String.Format(this._urlStr, $F(this._select), code, this._width, this._height, $F(this._kline), $F(this._tline), $F(this._dline)) + "?r=" + getRandom() : this._blank;
		this._currentCode = code;
	},
	
	_createSelect: function() {
		var html = '周期：<select id="{0}">'+
                            '<option value="min" selected>分时</option>' +
                            '<option value="min5">5分钟</option>' +
                            '<option value="min60">小时线</option>'+
                            '<option value="day">日线</option>' +
                            '<option value="week">周线</option>' +
                    '</select>' +
					'K线形态:<select id="{1}">' +
						'<option value=":LINERED" selected>线图</option>' +
						'<option value=":K">蜡烛图</option>' +
						'<option value=":BAR">美国线</option>' +
						'<option value=":TWR">宝塔线</option>' +
					'</select>' +
					'指标:' +
					'<select id="{2}">' +
						'<option value="" selected>选择指标</option>' +
						'<option value="+MA">MA均线</option>' +
						'<option value=":RSI">RSI</option>' +
						'<option value=":KDJ">KDJ</option>' +
						'<option value=":MACD">MACD</option>' +
					'</select>' +
					'系统:<select id="{3}">' +
						'<option value="" selected>选择系统</option>' +
						'<option value="+MMV" >移中平均</option>' +
						'<option value="+YTTL">倚天屠龙</option>' +
						'<option value="+BSSM">搏杀生命</option>' +
						'<option value="+BSCG">搏杀持仓</option>' +
					'</select><br/>';
		var typeId  = this.Id + "_type";
		var klineId = this.Id + "_kline";
		var tlineId = this.Id + "_tline";
		var dlineId = this.Id + "_dline";
		this.Dom.innerHTML += String.Format(html, typeId, klineId, tlineId, dlineId);
		this._select = $(typeId);
		this._kline = $(klineId);
		this._tline = $(tlineId);
		this._dline = $(dlineId);
		
		var me = this;
		var cb = function() { me.show(); };

		this._select.onchange = cb;
		this._kline.onchange = cb;
		this._tline.onchange = cb;
		this._dline.onchange = cb;
	},
	
	_createImg: function() {
		this._img = document.createElement("img");
		this._img.style.height = this._height + "px";
		this._img.style.width = this._width + "px";
		this.Dom.appendChild(this._img);
	}
}


