/*
* ActionQueue
* -----------------------
* @author       : Filatov Dmitry <alpha@design.ru>
* @last_modified: 09.03.2007
*/

function ActionQueue(sControllerUrl) {	
	
	this.sControllerUrl	= sControllerUrl;
	this.aActions = [];
	this.iLastProcessingCommandId = 0;

}

ActionQueue.TAG_REQUEST = 'request';

ActionQueue.prototype = {	
	
	addAction : function(oAction) {
	
		this.aActions.push(oAction);
		
		oAction.setId(this.aActions.length - 1);
		oAction.setStatus(Action.STATUS_IN_QUEUE);				
	
	},
	
	getActionById : function(iId) {
	
		if(this.aActions[iId]) {		
			return this.aActions[iId];		
		}
	
	},
	
	process : function() {		
	
		var
			sXml = '',
			bFireQueue = false
			;
		
		for(var i = this.iLastProcessingCommandId; i < this.aActions.length; i++) {
			
			if(this.aActions[i].getStatus() == Action.STATUS_IN_QUEUE) {
			
				sXml += '<' + Action.TAG + ' ' +
					Action.ATTR_ID + '="' + this.aActions[i].getId() + '\" ' +
					Action.ATTR_TYPE + '="' + this.aActions[i].getType() + '">' +
					this.aActions[i].getXml() +
					'</' + Action.TAG + '>';
			
				this.aActions[i].setStatus(Action.STATUS_PROCESSING);
				
				this.iLastProcessingCommandId = i;
				
				bFireQueue = true;
				
			}							
		
		}
		
		if(!bFireQueue) {
			return;
		}
		
		var aParams = [];		
		
		aParams['sData'] = '<' + ActionQueue.TAG_REQUEST + '>' + sXml + '</' +  ActionQueue.TAG_REQUEST + '>';
		
		var oAjaxHelper = new AjaxHelper(
			this,
			this.sControllerUrl,
			'POST',
			aParams
		);
		
		oAjaxHelper.send();
	
	},
	
	ajaxUpdate : function(oResponse) {
			
		try {
			
			var
				aResponseActions = oResponse.responseXML.getElementsByTagName(Action.TAG),
				oAction
				;		
			
			for(var i = 0; i < aResponseActions.length; i++) {
			
				oAction = this.getActionById(aResponseActions[i].getAttribute(Action.ATTR_ID));
				
				if(oAction) {
					
					oAction.setStatus(parseInt(aResponseActions[i].getAttribute(Action.ATTR_STATUS)));
					
					oAction.processResult(aResponseActions[i]);								
				
				}
			
			}
			
		}
		catch(oException) {
			alert(oException.message + '__');
			//alert("unhandled exception :: not valid response's xml");
		}
	
	}

};