// searches for ajaxable forms and hijacks them appropriately

var ajaxForms = {
	
	init : function(inTab, mbox){
		var that = this;
		// look for ajaxable forms
		document.querySelectorAll('form.ajax-submit').forEach(function(form){
			var customCallback = function(){}, callback = function(){}, temp, afterSubmit, noMessage;
	//		var backup = form.onsubmit;
	//		console.log(backup);
		
			//console.log(form);
			if (afterSubmit = form.getAttribute('afterSubmit'))
				customCallback = new Function(afterSubmit);
			
			afterSubmit = (afterSubmit = form.className.match(/(?:\s|^)after\-submit:([A-z\-]+)(?:\s|$)/)) ? afterSubmit[1] : '';
			
			//	console.log(afterSubmit);
			switch (afterSubmit){ 
				case 'clear':
					callback = function(){
						clearForm(form);
					};
				break;
				case 'redirect':
					callback = function(d){
						if (!d.response || d.response.type == 'pos'){ // assume its a redirect string. set cookie first so message will show after redirect
							if (d.response){
								cookies.set('message[type]', d.response.type, 1 / 3000); // expires in approx 30 seconds
								cookies.set('message[content]', d.response.content, 1 / 3000); // expires in approx 30 seconds
							}
							
							if (('' + form.getAttribute('action')).match(/^https?\:\/\/./)){
								window.location = form.getAttribute('action');
							}
							else {
								// hack because IE doesn't respect the base tag, and tries to use the current url as the base
								var base = ('' + window.location).substr(0, ('' + window.location).indexOf('/',8) + 1);
								//alert(base);
								window.location = base + form.getAttribute('action');
							}
						}
					};
					noMessage = true;
				break;
				case 'close':
					if (inTab)
						callback = function(){ tabDialogHelper.close(); };
					else
						callback = function(){ window.close() };
				break;
			}
			
			
			form.addEventListener('submit', function(e){
				if (!formCheck.check(this, 0, [0,10]))
					return killEvent(e);
				else /*if (miscInfo.authUserId || !form.classList.has('require-auth'))*/{
					var thisForm = this;
					return !actions.submitForm(this, function(d){
						if (!d.response || d.response.type == 'pos'){
							callback(d);
							customCallback(d);
						}
						else if (noMessage)
							mbox.showMessage(d.response.content, d.response.type);
					}, noMessage) || killEvent(e); // no message will be displayed until after redirect, if redirecting
				}
			}, 1);
		});
	}
};