/*
 * Copyright (c) 2009 The Olympos Development Team.
 * 
 * http://sourceforge.net/projects/olympos/
 * 
 * All rights reserved. This program and the accompanying materials are made
 * available under the terms of the Eclipse Public License v1.0 which
 * accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html. If redistributing this code, this
 * entire header must remain intact.
 */
Ext.namespace("cwe.editor.control");

cwe.editor.control.AmountField = function() {

};

cwe.editor.control.AmountField = Ext.extend(chi.editor.control.TextField, {
	initComponent : function() {
		var self = this;

		// var maskRe = new RegExp("[0-9.+*\/" + this.thousandsSeparator +
		// this.decimalSeparator + "-]");
		var maskRe = /[()0-9,. '+*\/-]/;

		Ext.apply(this, {
		    maskRe : maskRe,
		    msgTarget : "under",
		    enableKeyEvents : true,
		    cls : "amountField"
		});

		cwe.editor.control.AmountField.superclass.initComponent.apply(this, arguments);

		this.on("keypress", function(field, e) {
			if (e.getKey() == e.ENTER) {
				self.updateCalculatedValue();
			}
		});
		this.on("blur", function(field) {
			self.updateCalculatedValue();
		});
	}
});

cwe.editor.control.AmountField.prototype.validateValue = function(value) {
	var result = true;
	var removeMessage = true;

	if (isNaN(Number(this.normalizeSeparators(value)))) {
		// we also ignore symbols at first position
		if (value.substr(1).search(/[()+*\/-]/) != -1) {
			value = this.normalizeSeparators(value);
			var calculation = null;

			try {
				calculation = eval(value);
			} catch (e) {
				calculation = NaN;
			}

			if (!isNaN(Number(calculation))) {
				calculation = calculation.toFixed(2);
				this.calculatedValue = calculation;
				this.adjustNegativeMark(calculation);
				this.showMessage(chi.Dict.translate("Result") + ": " + cwe.Util.formatNumber(calculation));
				removeMessage = false;
			} else {
				result = false;
				this.markInvalid(chi.Dict.translate("Cannot calculate value"));
			}
		} else {
			result = false;
			this.markInvalid(chi.Dict.translate("Invalid value"));
		}
	} else {
		this.adjustNegativeMark(this.normalizeSeparators(value));
	}

	if (removeMessage) {
		this.calculatedValue = null;
		this.removeMessage();
	}

	return result;
};

cwe.editor.control.AmountField.prototype.adjustNegativeMark = function(value) {
	if (Number(value) < 0) {
		this.addClass("negativeNumber");
	} else {
		this.removeClass("negativeNumber");
	}
};

cwe.editor.control.AmountField.prototype.updateCalculatedValue = function() {
	if (this.calculatedValue) {
		this.setValue(this.calculatedValue);
		this.removeMessage();
		this.calculatedValue = null;
	} else {
		var formattedValue = this.getValue();

		if (formattedValue) {
			this.setValue(formattedValue);
		}
	}
};

cwe.editor.control.AmountField.prototype.setValue = function(newValue) {
	var value = newValue;

	if (newValue && newValue.trim() != "") {
		value = cwe.Util.formatNumber(newValue);
	}

	return cwe.editor.control.AmountField.superclass.setValue.call(this, value);
};

cwe.editor.control.AmountField.prototype.getValue = function() {
	return this.normalizeSeparators(cwe.editor.control.AmountField.superclass.getValue.call(this));
};

cwe.editor.control.AmountField.prototype.showMessage = function(message) {
	var el = this.getEl();

	if (el) {
		if (!this.messageEl) {
			this.messageEl = el.insertSibling("<div class='amountFieldMessage'></div>", "after");
		}

		this.messageEl.update(message);
	}
};

cwe.editor.control.AmountField.prototype.removeMessage = function() {
	if (this.messageEl) {
		this.messageEl.remove();
		delete this.messageEl;
	}
};

cwe.editor.control.AmountField.prototype.normalizeSeparators = function(oldValue) {
	var result = "";

	// result = oldValue.replace(new RegExp(this.thousandsSeparator, "g"), "");
	// result = result.replace(new RegExp(this.decimalSeparator, "g"), ".");

	var numbers = String(oldValue).match(/-?[0-9]+[0-9,. ']*/g);
	var toProcess = oldValue;

	if (numbers) {
		for ( var i = 0; i < numbers.length; i++) {
			var currNumber = numbers[i];
			var currPos = toProcess.indexOf(currNumber);

			result += toProcess.substr(0, currPos);

			var numberParts = currNumber.split(/[,. ']+/);

			if (numberParts) {
				var replacement = "";

				for ( var j = 0; j < numberParts.length - 1; j++) {
					replacement += String(numberParts[j]);
				}

				var lastPart = numberParts[numberParts.length - 1];

				if (numberParts.length > 1 && lastPart.length <= 2) {
					replacement += '.';
				}
				replacement += lastPart;

				result += replacement;
			} else {
				result += currNumber;
			}

			toProcess = toProcess.substr(currPos + currNumber.length);
		}
		result += toProcess;
	} else {
		result = oldValue;
	}

	return result;
};

