/*
* Action
* -----------------------
* @author       : Filatov Dmitry <alpha@design.ru>
* @last_modified: 09.03.2007
*/

function Action(
	sType,
	aData,
	aAddData,
	oController,
	sSuccessFunctionName,
	sErrorFunctionName
	) {

	this.iStatus = Action.Status_INITIALIZED;
	this.iId  = 0;
	this.sType = sType;
	this.aData = aData;
	this.aAddData = aAddData;		
	this.oController = oController;
	this.sSuccessFunctionName = sSuccessFunctionName;
	this.sErrorFunctionName = sErrorFunctionName;

}

Action.STATUS_INITIALIZED = 100;
Action.STATUS_IN_QUEUE    = 101;
Action.STATUS_PROCESSING  = 102;
Action.STATUS_COMPLETED   = 0;
Action.STATUS_EXCEPTION   = 1;

Action.TAG             = 'action';
Action.TAG_DATA        = 'data';
Action.TAG_ERROR       = 'error';
Action.ATTR_ID         = 'id';
Action.ATTR_TYPE       = 'type';
Action.ATTR_STATUS     = 'status';
Action.ATTR_ERROR_CODE = 'code';

Action.prepareXml = function(sXml) {
	
	var sResult = sXml.replace(/&/g, '&amp;');
	sResult = sResult.replace(/</g, '&lt;');
	sResult = sResult.replace(/>/g, '&gt;');
	
	return sResult;
  	
};

Action.prototype = {
	
	setId : function(iId) {
	
		this.iId = iId;
	
	},
	
	getId : function() {
	
		return this.iId;
	
	},
	
	getType : function() {
	
		return this.sType;
	
	},
	
	setStatus : function(iStatus) {
	
		this.iStatus = iStatus;
	
	},
	
	getStatus : function() {
	
		return this.iStatus;
	
	},
	
	getXml : function() {
	
		return this.dataToXml();
	
	},
	
	dataToXml : function() {			
	
		var sXml = '';

		this.aData.foreach(function(mKey, mData) {
			sXml += '<' + mKey + '>' + Action.prepareXml(mData.toString()) + '</' + mKey + '>';			
		});
		return sXml;
	
	},
			
	processResult : function(oActionXml) {
		
		if(this.getStatus() != Action.STATUS_COMPLETED) {
			
			alert("unhandled exception :: system error");
			
			return;
			
		}
		
		var
			aErrors = oActionXml.getElementsByTagName(Action.TAG_ERROR),
			aData = oActionXml.getElementsByTagName(Action.TAG_DATA)
			;
		
		if(aErrors.length > 0) {			
			return this.executeErrorFunction(aErrors[0].getAttribute(Action.ATTR_ERROR_CODE));
		}
		
		if(aData.length > 0) {
			return this.executeSuccessFunction(aData[0]);
		}
	
	},
	
	executeSuccessFunction : function(aResult) {
		
		if(this.oController && this.oController[this.sSuccessFunctionName]) {		
			
			this.oController[this.sSuccessFunctionName](aResult, this.aAddData);			
			
			return true;
			
		}
		
		return false;
	
	},
	
	executeErrorFunction : function(sSign) {
		
		if(this.oController && this.oController[this.sErrorFunctionName]) {		
			this.oController[this.sErrorFunctionName](sSign, this.aAddData);			
		}
	
	}
	
}