// class to handle actions called via ajax




function Actions(mbox){
	this.callbacks = {}; // array dynamically added to with each request
	var that = this;
	this.json = new JsonRequest();
	this.mbox = mbox;
	this.actionPath = 'ajax/';
};

// called on page load
Actions.prototype.init = function(mbox){
	this.mbox = mbox;
};
// called in page body
Actions.prototype.setPaths = function(actionPath){
	this.actionPath = actionPath;
};

// do an action from within js script etc
Actions.prototype.doAction = function(action, qs, callback, noMessage){
	var that = this, success = false;
	
	var lastRequest = function(){	
		//alert('hello');
		mbox.showMessage('Processing...', 'throbber');
		success = that.json.makeRequest(that.actionPath, 'action=' + action + '&' + qs, function(d){
			//that.callback(d, callback);
	

			if (d.response && !noMessage)
				this.mbox.showMessage(d.response.content, d.response.type);
			if (d.authError)
				ajaxLogin.showForm(d.carryAction ? function(){
					lastRequest();
				} : null);
			if (typeof callback == 'function')
				callback(d || {});
		
		});
	};
	lastRequest();

	return success;
};

// do action via an html form (relies on the form having the appropriate 'action' input).
Actions.prototype.submitForm = function(form, callback, noMessage){
	var that = this;
	base2.DOM.bind(form);
	
	return this.doAction('', this.parseFormToString(form), callback, noMessage);
};

/*
Actions.prototype.callback = function(d, callback){
	var that = this;
	//console.log(d);
};
*/

// returns a url string for get/post from a form
Actions.prototype.parseFormToString = function(form){
	
	var str = '', name, inputs = [
		form.getElementsByTagName('input'),
		form.getElementsByTagName('select'),
		form.getElementsByTagName('textarea')
	], 
	plus = '++'.substring(0,1);

	// Loop through each list of tags, constructing our string.
	for (var i = 0; i < inputs.length; i++){
		for (var j = 0; j < inputs[i].length; j++){
			if (inputs[i][j] && (name = inputs[i][j].getAttribute('name'))){
				var type = inputs[i][j].getAttribute('type');
				if (type != 'checkbox' && type != 'radio' || (type == 'checkbox' || type == 'radio') && inputs[i][j].checked)
					str += escape(name).replace(plus, '%2B') + '=' + escape(inputs[i][j].value).replace(plus, '%2B') + '&';
			}
		}
	}

	// Strip trailing ampersand, because we can :)
	return str.substring(0, str.length - 1);
};



