/*
@name: /htdocs/classes/FormChecker.js
@desc: Validatore delle form di iscrizione con supporto flash
@authors: Marco Biondi
@lastauthor: Marco Biondi
@require: FLASH Utils
*/

_dadanet.createClass( 'FormChecker', {
	_swfVersion: "1.002",
	_swfName: _imgDestDomain+"/general/swf/checkForm.swf",
	initialize: function(divID, opts) {
		this._container = $(divID);
	
		this.options = {
			formName: '',
			formFields: {},
			readyCallback: null,
			alertWarning: false,
			useSWF: true
		};
		Object.extend(this.options, opts || {});

		var def_FF =
		{
			appd: '',
			email: 'email',
			token: 'ottk',
			output: 'frmchksm'
		};
		Object.extend(def_FF, this.options.formFields || {});

		this.options.formFields = def_FF;

		this._swf = null;
		this._form = null;
		this._oID = 'swf_frmCHK';

		Binder.initialize(this);
		this.defineBind('trySubmit','submit', this._onSubmit, false);

		if(this.options.formName)
		{
			this._form = $(document.forms[this.options.formName]);
			this.bindFunction('trySubmit', this._form);
		}

		if(this.options.useSWF)
		{
			try
			{
				_dadanet.createSWFWrapper(this._oID, this);
			}
			catch(err)
			{
				return(null);
			}
	
		 	AC_FL_GenerateContentIn(
			 	this._container,
			 	[
					'codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0',
					'pluginspage','http://www.macromedia.com/go/getflashplayer',
					'id', this._oID,
					'name', this._oID,
					'width', 1,
					'height', 1,
					'align','middle',
					'quality','high',
					'bgcolor','#000000',
					'wmode','transparent',
					'menu','false',
					'allowscriptaccess','always',
					'swliveconnect', 'true',
					'flashvars','_objID='+this._oID,
					'src', this._swfName+"?v="+this._swfVersion,
					'movie', this._swfName+"?v="+this._swfVersion
				]);
		}
	},
	_SWFinit: function()
	{
		this._swf = _dadanet.getSWFObject(this._oID);
		if(typeof(this.options.readyCallback) == "function")
		{
			setTimeout(this.options.readyCallback, 10);
		}
		return(this.options);
	},

	_onSubmit: function(objEvt) {
		try
		{
			var res = checkForm(this._form, this.options.alertWarning);
			if(!res)
			{
				Event.stop(objEvt);
				return;
			}
		}
		catch(err)
		{
			console.debug(err);
		}

		this.validate(this._form);
	},

	validate: function(frm) {
		if(this._swf)
		{
			try
			{
				var myForm=$(frm);
				var cname = this.options.formFields['output'];
				var dati = myForm.serialize().toQueryParams();
				var res = this._swf.checkForm(dati);
				if(res[cname])
					myForm.elements[cname].value = res[cname];
			}
			catch(err)
			{
				console.debug(err);
			}
		}
	},

	initTnx: function(obj) {
		if(!this._swf)
		{
			setTimeout(this.initTnx.bind(this, obj), 500);
		}
		else
		{
			this._swf.initTnx(obj);
		}
	}
});