/***************************************************************
*  Copyright notice
*
*  (c) 2009 Stephan Schuler <stephan.schuler@netlogix.de>
*  All rights reserved
*
*  This script is part of the TYPO3 project. The TYPO3 project is
*  free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  The GNU General Public License can be found at
*  http://www.gnu.org/copyleft/gpl.html.
*  A copy is found in the textfile GPL.txt and important notices to the license
*  from the author is found in LICENSE.txt distributed with these scripts.
*
*
*  This script is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/



if (!nxajaxform)



/**
 * Ajax form transmission
 *
 * $Id$
 */
var nxajaxform = {




	init: function() {
		jQuery('.nx-ajaxform-wrapper').find('form').each(function(formKey, form) {
			nxajaxform.addSubmitWrapper(jQuery(form));
		});
		jQuery('form.nx-ajaxform').each(function(formKey, form) {
			nxajaxform.addSubmitWrapper(jQuery(form));
		});
	},




	addSubmitWrapper: function(form) {

		if (form.hasClass('nx-ajaxform-done')) {
			return false;
		}
		form.addClass('nx-ajaxform-done');

		form.submit(function(e) {
			e.preventDefault();
			return nxajaxform.submit(form, e);
		});

	},




	submit: function(form, event) {

//		var formValues = nxajaxform.getFormValues(form);
//		var queryString = nxajaxform.buildQueryString(form, formValues);
		queryString = form.serialize();
//		console.log(queryString);
		nxajaxform.runAjaxRequest(form, queryString);

		return false;

	},




	getFormValues: function(form) {

		var formValues = {};

		form.find(':input:enabled[name!=], :input[type=hidden][name!=]').each(function(inputKey, input) {
			inputElement = jQuery(input);
			if (
					inputElement.attr('type') == 'radio'
					||
					inputElement.attr('type') == 'checkbox'
				) {
				if(inputElement.attr('checked')) {
					nxajaxform.addFormValue(formValues, inputElement);
				}
			}
			else {
				nxajaxform.addFormValue(formValues, inputElement);
			}
		});

		return formValues;

	},




	addFormValue: function(formValues, inputElement) {
		if (!formValues[inputElement.attr('name')]) {
			formValues[inputElement.attr('name')] = [];
		}
		formValues[inputElement.attr('name')].push(inputElement.val());
	},




	buildQueryString: function(form, formValues) {

		var queryString = '';
		for (var key in formValues) {
			for (var i in formValues[key]) {
				queryString += key+'='+formValues[key][i]+'&';
			}
		};

		return queryString;

	},




	runAjaxRequest: function(form, queryString) {

		var action = form.attr('action');
		if (!action) {
			action = location.href;
		}

		if (action.search('\\?')!=-1) {
			action += '&';
		}
		else {
			action += '?';
		}
		nxajaxform.ajaxRequestCounter++;
		action += 'tx_nxajaxform[randomId]['+(nxajaxform.ajaxRequestCounter)+']='+(new Date().valueOf());

		var targetBox = nxajaxform.getTargetBox(form);

		var ajaxRequest = jQuery.ajax({
			type: 'POST',
			url: action,
			data: queryString,
			success: function(plainMessage, readyState) {
				nxajaxform.ajaxCallback(plainMessage, readyState, ajaxRequest, targetBox, action, queryString);
			}
		});

	},




	ajaxCallback: function(plainMessage, readyState, requestObject, targetBox, calledUrl, queryString) {

		var bodyPartBegin = plainMessage.search('\<body.*\>');
		var bodyPartEnd = plainMessage.search('\</body\>');
		if (bodyPartBegin == -1)
			bodyPartBegin = 0;
		if (bodyPartEnd == -1)
			bodyPartEnd = plainMessage.length;
		plainMessage = plainMessage.substr(bodyPartBegin, bodyPartEnd-bodyPartBegin);
		var targetParts = jQuery('<div />').html(plainMessage).find('.nx-ajaxform-answer');
		if (targetParts.length >= 1) {
			targetBox.html(targetParts.eq(0));
		}
		else {
			targetBox.html(plainMessage);
		}

		jQuery.each(nxajaxform.onCompleteFunctions, function(i, onCompleteFunctions) {
			onCompleteFunctions(plainMessage, readyState, requestObject, targetBox, targetParts, calledUrl, queryString);
		});

	},




	getTargetBox: function(form) {

		var targetElement = false;
		form.find('input.nx-tabform-response').each(function(inputKey, input) {
			var inputElement = jQuery(input);
			jQuery(inputElement.val()).each(function(targetBoxKey, targetBox) {
				if (!targetElement) {
					targetElement = targetBox;
				}
			});
		});

		return jQuery(
			targetElement
				? targetElement
				: '<div />'
		);

	},




	ajaxRequestCounter: 0,




	complete: function(functionReference, clear) {

		if (typeof clear == 'undefined') {
			nxajaxform.onCompleteFunctions = [];
		}
		if(typeof functionReference == 'function') {
			nxajaxform.onCompleteFunctions.push(functionReference);
		}

	},




	onCompleteFunctions: []




};




jQuery(document).ready(function () {
	nxajaxform.init();
});


