/* LimitsDrawer extends PlatformDrawer */

var LimitsDrawer = function() {}

LimitsDrawer.prototype = new PlatformDrawer();

LimitsDrawer.prototype._drawnPrice = function(row, index, signal) {
	var vPref = '<div class="value">';
	var vSuff = '</div>'
	var login = '<span class="login">login to get value</span>'
	var stopPref = '<div class="stop">';
	var stopSuff = '</div>';
	//conservative = high1, low1
	//agressive = high, low
	var conGainVal = '&nbsp;';
	var agGainVal = '&nbsp;';
	var conLossVal = '&nbsp;';
	var agLossVal = '&nbsp;';
	var conGainStop = '';
	var agGainStop = '';
	var conLossStop = '';
	var agLossStop = '';
	if (signal.hasLimits()) {
		conGainVal = '$ ' + signal.getStophigh1();
		agGainVal = '$ ' + signal.getStophigh();
		conLossVal = '$ ' + signal.getStoplow1();
		agLossVal = '$ ' + signal.getStoplow();
	} else if (signal.hasStopHash()) {
		conGainVal = agGainVal = conLossVal = agLossVal = login;
	}
	if (signal.hasStops()) {
		conGainStop = (signal.isStoppedByHigh1()) ? (stopPref + signal.getStophigh1Data() + stopSuff) : '';
		agGainStop = (signal.isStoppedByHigh()) ? (stopPref + signal.getStophighData() + stopSuff) : '';
		conLossStop = (signal.isStoppedByLow1()) ? (stopPref + signal.getStoplow1Data() + stopSuff) : '';
		agLossStop = (signal.isStoppedByLow()) ? (stopPref + signal.getStoplowData() + stopSuff) : '';
		//temporary!
//		conGainStop = (signal.isStoppedByHigh1()) ? (stopPref + 'limit reached' + stopSuff) : '';
//		agGainStop = (signal.isStoppedByHigh()) ? (stopPref + 'limit reached' + stopSuff) : '';
//		conLossStop = (signal.isStoppedByLow1()) ? (stopPref + 'limit reached' + stopSuff) : '';
//		agLossStop = (signal.isStoppedByLow()) ? (stopPref + 'limit reached' + stopSuff) : '';

	}
	this.addSpacer(row, index++);
	this.addCell(row, index++, (vPref + conGainVal + vSuff + conGainStop), "gain");
	this.addSpacer(row, index++);
	this.addCell(row, index++, (vPref + conLossVal + vSuff + conLossStop), "loss");
	this.addSpacer(row, index++);
	this.addCell(row, index++, (vPref + agGainVal + vSuff + agGainStop), "gain");
	this.addSpacer(row, index++);
	this.addCell(row, index++, (vPref + agLossVal + vSuff + agLossStop), "loss");
	index = this._drawnLimits(row, index, signal);
	return index;
}

LimitsDrawer.prototype._drawnLimits = function(row, index, signal) {
	return index;
}

/* LimitsExtenstion extends PlatformUpdateExtenstion */

var LimitsExtension = function(updatePeriodSeconds, stopPeriod, timeoutPeriod, requestUrl, loggedIn) {
	this.period = updatePeriodSeconds * 1000;
	this.stopPeriod = stopPeriod;
	this.timeoutPeriod = timeoutPeriod;
	this.requestUrl = requestUrl;

	this.signals = [];
	this.timer = null;

	this.block = false;
	this.request = null;
	this.requestCount = 0;
	this.currentStopPeriod = 0;

	this.loggedIn = loggedIn;
	this.initialized = false;

	this.interceptor = null;
}

LimitsExtension.prototype = new PlatformUpdaterExtension();

LimitsExtension.prototype.notify = function() {
	if (this.timer == null) {
		var thisClosure = this;
		this.timer = setInterval(function(){thisClosure.load(false);}, this.period);
		this.load(true);
	}
}

LimitsExtension.prototype.loginNotify = function(loggedIn) {
	this.loggedIn = loggedIn;
	this.notify();
}

LimitsExtension.prototype.addInterceptor = function(interceptor) {
	this.interceptor = interceptor;
};

LimitsExtension.prototype.load = function(ignoreStopPeriod) {
	if (this.block)
		return;
	if (this.requestCount != 0) {
		if (++this.requestCount > this.timeoutPeriod)
			this.abortRequest();
		else
			return;
	}
	var signalsList = this.pUpdater.signalsList.getLimitsActiveSignalsList(!this.loggedIn);
	this.signals = signalsList.getSignals();
	if (this.signals.length == 0) {
		clearInterval(this.timer);
		this.timer = null;
		return;
	}
	if (!ignoreStopPeriod && (!this.loggedIn || signalsList.allHaveLimits())) {
		if (++this.currentStopPeriod < this.stopPeriod)
			return;
	}
	this.currentStopPeriod = 0;
	this.makeRequest();
}

LimitsExtension.prototype.makeRequest = function() {
	this.request = ((typeof XMLHttpRequest != 'undefined') ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"));
	this.requestCount = 1;
	var url = this.requestUrl + "?requestId=" + (new Date().getTime());
	this.request.open("POST", url, true);
	this.request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	var reqClosure = this.request;
	var thisClosure = this;
	this.request.onreadystatechange = function() {
		if (reqClosure.readyState == 4) {
			thisClosure.processResponse(reqClosure.responseText);
			thisClosure.abortRequest();
		}
	}
	this.request.send(this.getSignaturesRequest());
}

//synchronized
LimitsExtension.prototype.processResponse = function(response) {
	if (this.block)
		return;
	this.block = true;
	try {
		var responseArray = eval(response);
		var changed = false;
		for (var i in this.signals) {
			for (var j in responseArray) {
				if (this.signals[i].getSignature() == responseArray[j]['signature']) {
					var signalChanged = this.signals[i].setStopHash(responseArray[j], changed);
					changed = changed || signalChanged;
					break;
				}
			}
		}
		if (changed) {
			if (!this.initialized) {
				this.initialized = true;
			} else if (this.initialized && this.interceptor) {
				if (this.interceptor.intercept())
					return;
			}
			this.pUpdater.draw();
		}
	} catch(e) {}
	this.block = false;
}

LimitsExtension.prototype.abortRequest = function() {
	this.requestCount = 0;
	this.request.abort();
	this.request = null;
}

LimitsExtension.prototype.getSignaturesRequest = function() {
	var result = "";
	var signals = this.signals;
	for (var i in signals) {
		if (i > 0)
			result += "&";
		result += "s=" + signals[i].getSignature();
	}
	return result;
}

/* Signal Prototype Extenstion */

Signal.prototype.stopHash = null;

Signal.prototype.setStopHash = function(stopHash, skipCheck) {
	if (skipCheck ||
		!this.hasStopHash() ||
		(!this.hasStops() && (typeof stopHash['stopped'] != 'undefined') ||
		(!this.hasLimits() && (typeof stopHash['low'] != 'undefined'))) ||
		(
			this.hasStops() &&
			((this.isStopped() != stopHash['stopped']) ||
			(this.isStoppedByLow() != stopHash['stoppedByLow']) ||
			(this.isStoppedByLow1() != stopHash['stoppedByLow1']) ||
			(this.isStoppedByHigh() != stopHash['stoppedByHigh']) ||
			(this.isStoppedByHigh1() != stopHash['stoppedByHigh1']))
		))
	{
		if (this.hasLimits() && (typeof stopHash['low'] == 'undefined')) {
			this.stopHash['stoppedByLow'] = stopHash['stoppedByLow'];
			this.stopHash['stoppedByLow1'] = stopHash['stoppedByLow1'];
			this.stopHash['stoppedByHigh'] = stopHash['stoppedByHigh'];
			this.stopHash['stoppedByHigh1'] = stopHash['stoppedByHigh1'];
			this.stopHash['stopped'] = stopHash['stopped'];
		} else {
			this.stopHash = stopHash;
		}
		return true;
	}
	return false;
}

Signal.prototype.hasStopHash = function() {return (this.stopHash != null);}

Signal.prototype.hasLimits = function() {return (this.hasStopHash() && (typeof this.stopHash['low'] != 'undefined'));}

Signal.prototype.hasStops = function() {return (this.hasStopHash() && (typeof this.stopHash['stopped'] != 'undefined'));}

Signal.prototype.getStoplow = function() {return this.get('low');}

Signal.prototype.getStoplow1 = function() {return this.get('low1');}

Signal.prototype.getStophigh = function() {return this.get('high');}

Signal.prototype.getStophigh1 = function() {return this.get('high1');}

Signal.prototype.isStoppedByLow = function() {return this.get('stoppedByLow');}

Signal.prototype.isStoppedByLow1 = function() {return this.get('stoppedByLow1');}

Signal.prototype.isStoppedByHigh = function() {return this.get('stoppedByHigh');}

Signal.prototype.isStoppedByHigh1 = function() {return this.get('stoppedByHigh1');}

Signal.prototype.getStoplowData = function() {return this.getData('stoplow');}

Signal.prototype.getStoplow1Data = function() {return this.getData('stoplow1');}

Signal.prototype.getStophighData = function() {return this.getData('stophigh');}

Signal.prototype.getStophigh1Data = function() {return this.getData('stophigh1');}

Signal.prototype.isStopped = function() {return (this.hasStops() && this.stopHash['stopped']);}

Signal.prototype.get = function(name) {return this.stopHash[name];}

Signal.prototype.getData = function(name) {
	if (typeof this.stopHash[name] == 'undefined')
		return 'limit reached';
	var hash = this.get(name);
	return (hash['glper'] + '% (' + hash['time'] + ')');
}


/* SignalsList prototype Extenstion */

SignalsList.prototype.getLimitsActiveSignalsList = function(onlyByStops) {
	var result = new LimitsActiveSignalsList(onlyByStops);
	var signals = this.getAll();
	for (var i in signals)
		result.addSignal(signals[i]);
	return result;
}

/* LimitsActiveSignalsList */

var LimitsActiveSignalsList = function(onlyByStops) {

	this.signals = [];
	this.nonLimitsNumber = 0;

	this.addSignal = function(signal) {
		if (onlyByStops && signal.isStopped())
			return;
		if (!onlyByStops && signal.hasLimits() && signal.isStopped())
			return;
		if (!signal.hasLimits())
			this.nonLimitsNumber++;
		this.signals.push(signal);
	}

	this.getSignals = function() {
		return this.signals;
	}

	this.allHaveLimits = function() {
		return (this.nonLimitsNumber == 0);
	}
}