var webform = liwe.module ( "webform" );

webform._dests = null;
webform._dest_div = null;

webform.init = function ()
{
	webform.load_templates ();
};

webform.dynamic_form = function ( form_name, dest_div, cback )
{
	webform.ajax ( { action: "webform.ajax.get_form_fields", fname: form_name } , function ( vars )
					{
						var ffields = vars.get ( 'ffields', [] );
						if ( ffields.count () < 1 )	
						{
							if ( cback ) cback ();
							return;
						}
						var fname = ffields[0] [ 'name' ];
						var f = new liwe.form.instance ( fname );
						ffields.iterate ( function ( v, k ) {
											f [ v [ 'field' ] ] ( v [ 'args' ] );
										     } );
						f.button ( { value: "Invia", onclick: "webform._send ( '" + dest_div + "','" + fname + "');" } );
						f.set ( dest_div );
					} );
};

webform._send = function ( dest_div, fname )
{
	var f = liwe.form.get ( fname );
	var args;

	if ( ! f.check () ) return;

	args = f.get_values ();

	args [ 'action' ] = "webform.ajax.send_form";

	liwe.AJAX.easy ( args, function ( v )
		{
			$( dest_div, "Messaggio inviato con successo!" );
		} );
};

webform.plugin = function ( div, params )
{
	div.id = "plugin:webform:" + params [ 'name' ];
	webform.dynamic_form ( params [ 'name' ], div.id, function ()
		{
			div.style.display = 'none' 
			console.error ( 'webform.plugin: webform %s doesn\'t exists!', params [ 'name' ] );
		} );
};



/* DEPRECATED
webform.create = function ( dest_div )
{
	if ( ! dest_div ) dest_div = webform._dest_div;
	webform._dest_div = dest_div;
		
	if ( ! webform._dests )
	{
		webform.ajax ( { "action" : "webform.ajax.list_destinations" }, function ( v )
			{
				webform._dests = v [ 'destinations' ];
				webform._show ();
			} );

	} else
		webform._show ();
};
webform._show = function ()
{
	var f = new liwe.form.instance ( "webform-request" );

	f.select ( { label: "Argomento", name: "id_dest", options: webform._dests, mandatory: true, force_select: true } );
	f.email ( { label: "Il tuo indirizzo di email", name: "sender_email", size: 40, maxlength: 100, mandatory: true } );
	f.textarea ( { label: "Messaggio", name: "message_body", rows: 10, cols: 70 } );
	f.button ( { value: "Invia", onclick: "webform._send()" } );

	f.set ( webform._dest_div );
};
*/

