Ext.namespace('TJ.Admin');


// Forms
TJ.Admin.FormLayout = Ext.extend(Ext.layout.FormLayout, 
{
    getTemplateArgs: function(c) { 
//		console.log('flds',c);
			return [
                   c.id, c.fieldLabel,
                   (c.labelStyle||this.labelStyle||''),
                   this.elementStyle||'',
                   typeof c.labelSeparator == 'undefined' ? this.labelSeparator : c.labelSeparator,
                   (c.itemCls||this.container.itemCls||'') + (c.hideLabel ? ' x-hide-label' : '') + (c.disableField ? ' disableField' : '') ,
                   c.clearCls || 'x-form-clear-left' ,
				   c.desc||'',
				   c.narrative||'',
				   (c.narrative) ? ' border-bottom:1px dashed #00CC00; cursor:help;':'',
				   (c.subheading)? '<div class="FieldSubheading">'+c.subheading + '</div>' :'',
				   (c.heading)? '<div class="FieldHeading">'+c.heading + '</div>' :'',
					(c.allowBlank) ? ( c.langRequired ? 'required single':''): 'required'
            ];
	},
	labelSeparator:'',
	fieldTpl: (function() {
            var t = new Ext.Template(
                '<div class="x-form-item {5}" tabIndex="-1">',
					'{11}',
					'{10}',
                    '<label for="{0}" style="{2}" class="x-form-item-label {12}"><span style="{9}" title="{8}">{1}</span>{4}</label>',
                    '<div class="x-form-element" id="x-form-el-{0}" style="{3}">',
                    '</div><div class="FieldDesc" style="{3}">{7}</div><div class="{6}"></div>',
                '</div>');
            t.disableFormats = true;
	        return t.compile();
    })()
 });
Ext.Container.LAYOUTS['tjadminform'] = TJ.Admin.FormLayout;

TJ.Admin.FieldSet = Ext.extend(Ext.form.FieldSet,{
    layout: 'tjadminform'
});

/*
TJ.StandardRequest= function(config) {
	Ext.apply(config,	{callback: function (options,success, response) {
		var res=TJ.Admin.ProcessJSONResponse(options,success, response);
	} });
	Ext.Ajax.request ( config);

};
*/

Ext.reg('tjfieldset',TJ.Admin.FieldSet);

	TJ.Admin.StatusPanelForm = Ext.extend(Ext.Panel, {
				errorIconCls : 'x-form-invalid-icon',
				validIconCls : 'x-status-valid',

		autoScroll: true,
		border: false,
		layout: 'fit',

		setDefault: function(button){
			if(button.field){
				button.field.setValue(button.field['default']);
				button.field.focus();
				TJ.Admin.statusGrid.addMessage({message:String.format('Field {0} reset to default',button.field.fieldLabel)});
			}
			else {
				Ext.Msg.confirm('Please confirm','Revert all fields to their defaults',
					function(btn){
						if(btn == 'yes'){
							this.form.items.each(function(f) {
									f.setValue(f['default']); 
							},this);
							TJ.Admin.statusGrid.addMessage({message:String.format('All {0} fields reset to their defaults',this.title)});
						}
					},this);
			}
		},
		initComponent: function() {
//			this.formconfig.border=false;
//			console.log('formconfig',this.formconfig);
			this.items=  this.form = new TJ.Admin.Form( this.formconfig);


			this.bbar =  new Ext.StatusBar({
				iconCls: 'ready-icon',
	            defaultText: 'Ready'
//				,				plugins: new Ext.ux.ValidationStatus({form: this.form.getId()})
			});
			if(this.revert){
				var items=[];
				this.form.items.each(function(f){ items.push(	{	text: f.fieldLabel,
																	field: f});},this);

				this.defaultButton = new  Ext.SplitButton({
						text: 'Set to default:  All Fields',
						iconCls: 'icon_arrow_undo',
						handler: this.setDefault,
						field: null,
						scope: this,
						menu:new Ext.menu.Menu({
								defaults: {
									iconCls: 'icon_arrow_undo',
									handler: this.setDefault
								},
								items: items
							})
				});



				this.tbar = [this.defaultButton];

			}




			TJ.Admin.StatusPanelForm.superclass.initComponent.call(this);

			this.form.on('failed', function(message){
				this.getBottomToolbar().setStatus( {text: message, iconCls: 'x-status-error'});				

			},this);

			this.form.on('actioncomplete',function(form,action) {
				this.getBottomToolbar().clearStatus();
			},this);
		},
		render: function(ct,pos){
				// this is to clean up the loading mask for client forms.
				// Better to create a client facing form.
			if(Ext.get(ct).hasClass('x-mask-loading')) {
				Ext.get(ct).removeClass('x-mask-loading');

				div=Ext.get(ct).first();
				if(div)
					div.remove();
			}
			TJ.Admin.StatusPanelForm.superclass.render.call(this,ct,pos);
		}
	});

Ext.reg('tjstatuspanelform',TJ.Admin.StatusPanelForm);

	TJ.Admin.Form = Ext.extend(Ext.FormPanel,{
		frame: true,
		layout: 'tjadminform',
		labelAlign: 'right',
		autoScroll: true,
		labelWidth: 145,
		fileUpload: false,
		notifyComponent: null,
		params: {},
		focus: true,
		defaults: {	selectOnFocus: true,
		            msgTarget: 'side'

		  		  },
		render: function(ct,pos){
			TJ.Admin.Form.superclass.render.call(this,ct,pos);
			if(this.focus)
				this.focusFirst();

		},
		initComponent:function() {
			if(this.buttons) {
				var i=0;
				while(this.buttons[i]) {
					this.buttons[i].handler=this.doSubmit;
					this.buttons[i].scope=this;
					if(i===0)
						this.buttons[i]['default']=true;
					i=i+1;
				}
			}
			else {
				this.buttons=[ { text: 'Save',
								 scope: this,
								 handler: this.doSubmit,
								 'default': true}];
								


			}


			for( i=0; i<this.items.length;i++){
				if (this.items[i].xtype=='tjuserfile')
				{
					this.fileUpload=true;
					break;
				}
			}

			TJ.Admin.Form.superclass.initComponent.call(this);
			this.form.trackResetOnLoad=true;
			// Enable autosubmit from any field type.
			this.fieldArray={};
			this.items.each(function(f){
				f.on('dosubmit',this.doSubmit,this);
				f.on('focus',this.fieldFocus,this);
				if(f.getName)
					this.fieldArray[f.getName()]=f.getId();
			},this);

			this.items.each(function(f){
				f.fieldArray=this.fieldArray;
			},this);

			this.on('actioncomplete', function(form,action){
				this.getEl().unmask();
				if(action.result)
					TJ.Admin.ProcessStandardResponse(action.result);
				if(this.callback){
//					console.log('new',this.scope);
					this.callback.call(this.scope||this,action.result,action,this);


				}
			});
			this.on('actionfailed', function(form,action){
				this.getEl().unmask();
				if(action.failureType == Ext.form.Action.SERVER_INVALID){
					if(action.result) {
						TJ.Admin.ProcessStandardResponse(action.result);

					if(action.result.errors)
						form.items.each(function(f){
									if(action.result.errors[f.name||f.getName()]) {	f.focus(true,true); return false;}
								});
						if(action.result.errors.__form__){
							this.fireEvent('failed',action.result.errors.__form__);

						}
					}
				} else
				if(action.failureType == Ext.form.Action.CLIENT_INVALID){
					this.focusInvalidField();
				} else {
					if(action.result) {
						TJ.Admin.ProcessStandardResponse(action.result);

					}
				}
			});
		},
		fieldFocus: function(field){
			this.fireEvent('fieldFocus',field);
		},
		doSubmit: function(field){
			if(tinyMCE) tinyMCE.triggerSave();
				this.getForm().submitValue = field.value || 'default';
				if(this.getForm().isValid()){
					this.getEl().mask('Processing...','x-mask-loading');

					this.getForm().baseParams=this.getForm().baseParams || {};
					this.getForm().baseParams._formId=this.getId();
					this.getForm().baseParams._submit=this.getForm().submitValue;
//				console.log(this.getForm());

					this.getForm().doAction('tjsubmit',{});
				}
				else
					this.focusInvalidField();

			},
		focusInvalidField: function(){
				this.items.each(function(f){ if(! f.isValid()) {f.focus(true,true); return false;}});

				this.fireEvent('failed','There are errors in your input');
			},
		focusFirst: function(){
				this.items.each(function(f){ if(!f.disabled) {f.focus(true,true); return false;}});
			}
	});

// Form Handling override for Submit to handle invalid JSON return value;

TJ.formSubmit=Ext.extend(Ext.form.Action.Submit,{
	handleResponse: function(response){
		try
		{
			return TJ.formSubmit.superclass.handleResponse.call(this,response);
		}
		catch (ex)
		{
			console.log('Form Processing Error:',response,ex);
			return { success: false,
					 errors : { __form__: "We were unable to process your form.  Please try again"},
					 alert: { title: 'Error',message: "We were unable to process your form.  Please try again.<BR>" + ex.name + ': ' + ex.message + '<BR>' + response.responseText }
			};
		}
	}
});
Ext.form.Action.ACTION_TYPES.tjsubmit=TJ.formSubmit;





TJ.Admin.FormPlugin = (function() {

    return {

        init: function(form) {
			var fieldChange=function(f) {
				form.items.each(function(i){
					if(i.siblingChange)
						i.siblingChange(f);
					if(i.enableField == f.name) {
						i.setDisabled(f.getValue());
					}
					if(i.disableField == f.name){
						i.setDisabled(! f.getValue());
					}
				});


			};

		Ext.apply(form, {
			onRender: form.onRender.createSequence(function(ct, position) {

				this.items.each(function(i){
					i.on('change',fieldChange,form);
					i.on('select',fieldChange,form);		// for combos.
					fieldChange(i);
				});
				console.log('do an initial run!',form);
//				fieldChange(form);

			})
		});
	}

        };
    });
