var mod_myform = function(){

    // shorthands
   	var Tree = Ext.tree;
	var dc = new Ext.data.Connection;
	var dt = new Ext.util.DelayedTask();
	var dh = Ext.DomHelper;
	
	return {

		// public vars
		json: {},
		forms: {},
		
		// constructor
		init : function()
		{
			Ext.QuickTips.init();
			
			// custom Vtype for vtype:'number'
			Ext.apply(Ext.form.VTypes, {
				number:  function(v) {
					return /^[-]?([1-9]{1}[0-9]{0,}(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|\.[0-9]{1,2})$/.test(v);
				},
				numberText: $l('error_message_invalid_number'),
				numberMask: /[-+0-9.]/
			});
			
			// multiple forms per page possible
			for(var uid in Ext.inCMS.myform)
			{
				if(Ext.inCMS.myform[uid]['mode'] == 'form')
				{
					this.json[uid] = Ext.inCMS.myform[uid];
				
					if(!this.json[uid]['edit'])
					{
						this.buildForm(uid);
					}
				}
			}
		},
		
		buildForm: function(contUid)
		{
			// build auth
			
			var cont = Ext.get('myform_' + contUid);
			if(cont)
			{
				// basic settings
				var def = {
					fileUpload: true,
					border: false,
					url: this.json[contUid].dataUrl + '&cmd=submit',
					waitMsgTarget: true,
				    renderTo: 'myform_' + contUid,
				    defaults: {
				    	labelSeparator: ''
				    },
				    labelWidth: 100,
				    //title: 'test',
				    items: [],
				    buttons: []
				};
				
				var contDefaultConfig;
				if(contDefaultConfig = Ext.inCMS.myform[contUid]['config']) Ext.apply(def, contDefaultConfig);
				
				var formSub, formSubJson;
				
				cont.select('.myformchild').each(function()
				{
					// if the sub content div has another div with class myform, it's a form element
					formSub = this.child('.myformsub');
					if(formSub)
					{
						uid = formSub.id.substring(10);
						if(Ext.inCMS.myform[uid]['mode'] != 'form')
						{
							formSubJson = Ext.inCMS.myform[uid];
							formSub = Ext.get('myformsub_' + uid);
						
							var elLabel = formSub.child('label');
							if(elLabel)
							{
								var el = formSub.child('.myformel'),
								elDom = el.dom,
								elTag = Ext.util.Format.lowercase(elDom.tagName),
								newItem = {};
								
								Ext.apply(newItem, formSubJson.config);
								
								newItem.name = 'data[' + elDom.name + ']';
								newItem.fieldLabel = formSub.child('label').dom.innerHTML;
								if(!newItem.fieldLabel) newItem.hideLabel = true;
								if(!newItem.width) newItem.width = elDom.style.width?elDom.style.width:formSubJson.paneWidth - def.labelWidth - 10;
								newItem.itemCls = el.dom.className;
								
								// apply optional xtype presets
								if(newItem.required) newItem.allowBlank = false;
								
								switch(true)
								{
									case elTag == 'input' && elDom.type == 'text':
										newItem.xtype = 'textfield';
									break;
									
									case elTag == 'input' && elDom.type == 'file':
										newItem.xtype = 'fileuploadfield';
										newItem.name = elDom.name;
									break;
									
									case elTag == 'textarea':
										newItem.xtype = 'textarea';
									break;
									
									case elTag == 'select':
										newItem.xtype = 'combo';
										newItem.store = [];
										newItem.triggerAction = 'all';
										newItem.forceSelection = true;
										newItem.hiddenName = newItem.name;
										newItem.name = '';
										
										el.select('option').each(function(){
											newItem.store[newItem.store.length] = [this.dom.value, this.dom.text];
										});
									break;
									
									case elTag == 'input' && elDom.type == 'checkbox':
										newItem.xtype = 'checkbox';
										newItem.inputValue = elDom.value;
										// if form is set to labelAlign = top, doesn't work well for checkboxes
										if(newItem.labelAlign == 'left')
										{
											newItem.hideLabel = true;
											newItem.boxLabel = newItem.fieldLabel;
										}
									break;
									
									default:
										newItem.xtype = 'radiogroup';
										newItem.columns = 1;
										
										var radioChildren = formSub.select('input'), radioChildrenCnt = radioChildren.elements.length, cnt = 0;
										var radioOpts = [];
										
										formSub.select('.option').each(function(){
											// we have to copy all newItem Options, else we just have a reference to the last option											
											var radioOpt = {};
											
											radioOpt.name = newItem.name;
											radioOpt.inputValue = this.child('input').dom.value;
											radioOpt.boxLabel = this.child('span').dom.innerHTML;
											
											radioOpts[radioOpts.length] = radioOpt;
											
											cnt++;
										});
										
										// don't add, all done
										newItem.items = radioOpts;
									break;
								}
							}
							
							if(newItem) def.items[def.items.length] = newItem;						
						}
					}	
					else
					{
						def.items[def.items.length] = {
							xtype: 'box',
							el: this.dom.id
							
						};
					}
				});
				
				//console.debug(def.items);
				//console.debug(cont.child('input:last'));
				var submitBtn = cont.child('input:last').dom;
				
				def.buttons[def.buttons.length] = {
					text: submitBtn.value,
					handler: this.formSubmit,
					scope: {
						uid: contUid
					}
				};
				
				this.forms[contUid] = new Ext.FormPanel(def);
				
				//Ext.fly('myform_' + contUid + '_form').remove();
			}
			
			
		},
		
		formSubmit: function()
		{
			var panel = mod_myform.forms[this.uid], frm = panel.getForm();
			
			var opts = {
				success: mod_myform.submitResponse,
				failure: Ext.base.responseMsg,
				waitMsg: 'Sending'
			};
			
			frm.submit(opts);
		},
		
		submitResponse: function(fp, response)
		{
			var params = response.options.params;
			var data = Ext.decode(response.response.responseText);
			
			
			if(data['redirect'])
			{
				window.location.href = data['redirect'];
			}
			else
			{
				Ext.MessageBox.show({
		           title: data.title || '',
		           msg: data.msg,
		           buttons: Ext.MessageBox.OK,
		           icon: Ext.MessageBox.INFO
				});
				
				fp.reset();
			}
		}
	};
}();

Ext.onReady(mod_myform.init, mod_myform);
