/**
  * FormManager Class
  *
  * @author  Marc Mignonsin
  * @version 2010-12-16
  *
  * @class FormManager
  * @constructor
  * @param
  */

FormManager = function(panelID, controller, script, method, dataResponseType)
{
	//window.log('FormManager', arguments);
	$('#'+panelID+'.panel').panel('addExternalResource', this, null);
	
	this.reset(); // just in case
	
	this.panelID = panelID;
	
	method = (method) ? method : 'json';
	this.ajaxRequest= new AjaxRequest(panelID, controller, script, 'POST', method); // frequently used values
	
	// display all errors, warnings, infos
	this.ajaxRequest.errorDialog(true, false); 
	this.ajaxRequest.internalErrorDialog(true, false);
	this.ajaxRequest.warningDialog(true, false); 
	this.ajaxRequest.infoDialog(true); 
	
	////window.log(this);

	return this;
};

FormManager.prototype.panelID = null;
FormManager.prototype.ajaxRequest = null;
FormManager.prototype.activeForm = '';
FormManager.prototype.parsedData = { };
FormManager.prototype.parsedFiles = [];
FormManager.prototype.defaultValues = { };
FormManager.prototype.requiredClass = 'required';
FormManager.prototype.abortSend = false;

FormManager.prototype.reset = function()
{
	//window.log('FormManager.reset', arguments);
	this.panelID = null;
	this.ajaxRequest = null;
	this.activeForm = null;
	this.parsedData = { };
	this.parsedFiles = [];
	this.defaultValues = { };
	this.requiredClass = 'required';
	this.abortSend = false;
};

FormManager.prototype.destroy = function()
{
	//window.log('FormManager.destroy', arguments);
	
};

/* *** */

FormManager.prototype.abortRequest = function()
{
	//window.log('FormManager.abortRequest', arguments);
	if ((typeof this.ajaxRequest !== 'undefined') && (this.ajaxRequest !== null))
	{
		this.ajaxRequest.abort();
        //window.log('aborted');
	}
};

FormManager.prototype.setScript = function(script)
{
	//window.log('FormManager.setScript', arguments);
	this.ajaxRequest.setScript(script);
};

FormManager.prototype.setResponseType = function(type)
{
	//window.log('FormManager.setResponseType', arguments);
	this.ajaxRequest.setResponseType(type);
};

FormManager.prototype.setActiveForm = function(formSelector)
{
	//window.log('FormManager.setActiveForm', arguments);
	//this.activeForm = $('#'+this.panelID+'.panel').find(formSelector);
	// less restrictive : allow form to be outside the panel => useful for modal dialog (e.g. system/tools/report/List.xsl) 
	this.activeForm = $(formSelector);
	//window.log(this.activeForm);
};

FormManager.prototype.getActiveForm = function()
{
	//window.log('FormManager.getActiveForm', arguments);
	return this.activeForm;
};

FormManager.prototype.addDefaultValue = function(key, value, defaultColor)
{
	//window.log('FormManager.addDefaultValue', arguments);    
	this.defaultValues[key] = value;
};

FormManager.prototype.resetLastParsing = function()
{
	//window.log('FormManager.resetLastParsing', arguments);
    this.parsedData = { };
    this.parsedFiles = [];
};

FormManager.prototype.onSuccess = function(callback)
{
	//window.log('FormManager.onSuccess', arguments);
	this.ajaxRequest.onSuccess(callback);
};

FormManager.prototype.onError = function(callback)
{
	//window.log('FormManager.onError', arguments);
	this.ajaxRequest.onError(callback);
};

FormManager.prototype.resetForm = function()
{
	this.activeForm.reset(); // jQuery extension
};

FormManager.prototype.parse = function(formSelector)
{
	//window.log('FormManager.parse', arguments);
	if (formSelector) this.setActiveForm(formSelector);

    this.resetLastParsing();

	var fm = this;
	var currentElem, key, value;
	var formElems = this.activeForm.find(':input[name]');
    //window.log(formElems);

	// input, select, textarea
	formElems.filter(':not(input:checkbox,input:radio,input:file)').each(function() {
		currentElem = $(this);

		key = currentElem.attr('name');
		value = currentElem.val();

		//window.log(key, value);
		//window.log('reset value', fm.defaultValues[key]);
        if (value != fm.defaultValues[key]) // do not send this
        {
            fm.addData(key, value);
        }
	});

	// radio
	formElems.filter('input:radio:checked').each(function() {
		currentElem = $(this);

		key = currentElem.attr('name');
		value = currentElem.val();

		//window.log('radio', key, value);
		fm.addData(key, value);
	});

	// checkbox
	formElems.filter('input:checkbox').each(function() {
		currentElem = $(this);

		key = currentElem.attr('name');
		value = (currentElem.attr('checked') == true) ? '1' : '0';

		//window.log('checked', key, value);
		fm.addData(key, value);
	});

    // files
	formElems.filter('input:file').each(function() {
		currentElem = $(this);
		//window.log(currentElem.val());
        if (currentElem.val() != '')
        {
        	// AjaxRequest will need the IDs to build an iFrame form...
            key = currentElem.attr('id'); 
            
            if (key)
            {
            	fm.addFile(key);
            }
            else
            {
            	fm.abortSend = true;
            	var msg = 'Parse error : a file input with no ID attribute has been found!<br /><br />Please specify an ID for all file inputs.';
            	fm.ajaxRequest.notifyApplicationError(msg);
            }
        }
	});

	//window.log(this.parsedData);
	//window.log(this.parsedFiles);
	return this.parsedData;
};

FormManager.prototype.getData = function(key)
{
	//window.log('FormManager.getData', arguments);
	return this.parsedData[key];
};

FormManager.prototype.getAllData = function()
{
	//window.log('FormManager.getAllData', arguments);
	return this.parsedData;
};

FormManager.prototype.getAllFiles = function()
{
	//window.log('FormManager.getAllFiles', arguments);
	return this.parsedFiles;
};

FormManager.prototype.addData = function(key, value)
{
	//window.log('FormManager.addData', arguments);
    //value = value.replace(/\"/g,"\\\""); // addslashes
	var keyLength = key.length;
	if ((key[keyLength-2] == '[') && (key[keyLength-1] == ']'))
	{
		key = key.substr(0, keyLength-2);
		
		if (this.parsedData[key])
		{
			this.parsedData[key].push(value);
		}
		else
		{
			this.parsedData[key] = [value];
		}
	}
	else
	{
		this.parsedData[key] = value;
	}
	//window.log(this.parsedData[key]);
};

FormManager.prototype.addFile = function(inputKey)
{
	//window.log('FormManager.addFile', inputKey);
    this.parsedFiles.push(inputKey);
};

FormManager.prototype.parseAndSend = function(formSelector, data, files)
{
	//window.log('FormManager.parseAndSend', arguments, this.scriptURL);
    this.parse(formSelector);
    return this.send(data, files);
};

FormManager.prototype.send = function(data, files)
{
	//window.log('FormManager.send', arguments, this.scriptURL);
	if (this.abortSend == true) // see parse()
	{
		this.abortSend = false;
		return false;
	}

	var requiredElems = this.activeForm.find(':input.'+this.requiredClass);
	if (requiredElems.length > 0) // discard
	{
		this.ajaxRequest.errorDialog(true, false);
		
		var msg = 'Warning : the following values are required to perform this operation:<br /><br />';
		
		var requiredLabels = [];
		requiredElems.parent('.field-value').prev('.field-name').each(function(){
			requiredLabels.push($(this).text().replace(/\:/g, '').replace(/\*/g, ''));			
		});
		
		msg += requiredLabels.join(', ')+'<br /><br />Please verify that all required values are specified and try again.';
		
		this.ajaxRequest.notifyApplicationError(msg);
		return false;
	}
	
	if (data) this.parsedData = data;
	if (files) this.parsedFiles = files;
    //window.log(this.parsedData);
    //window.log(this.parsedFiles);

	this.ajaxRequest.setData(this.parsedData);
	this.ajaxRequest.setFiles(this.parsedFiles);
	
    return this.ajaxRequest.send();
};

FormManager.prototype.displayProcess = function(msg)
{
    //window.log('FormManager.displayProcess', arguments);
    this.ajaxRequest.processingDialog(true, msg);
};

FormManager.prototype.onSuccessMessage = function(msg)
{
	//window.log('FormManager.onSuccessMessage', arguments);
	this.ajaxRequest.successDialog(true, msg, 'Ok', 1500);
};