/**
 * @author Piotr
 */
/**
 * @author piotr
 */



Ext.ns('App');

App.ValidationForm = Ext.extend( Ext.form.BasicForm,{
	errorLabelCls: 'validation-error',
	errorFieldCls: 'validation-error-field',
	errorContainerCls:'validation-error-container',
	
	constructor: function(htmlForm,errors,config){
		
		if( !config ) config = {};
		
		if (config.standardSubmit == null) {
			config.standardSubmit = true;
		}
		
		App.ValidationForm.superclass.constructor.call(this,htmlForm,config);
		
		this.addListener('actioncomplete',this.onActionComplete,this);
		this.addListener('actionfailed',this.onActionFailed,this);
		this.addListener('beforeaction',this.onBeforeAction,this);
		
		this.addEvents({
			'saved':true
		});
		

		
		if( errors ){
			for( field in errors ){
				if( field )
				this.markInvalidField( this.getEl(), field, eval( "errors."+field ) );
			}
		}
		
		this.applyInputHelps( htmlForm );
		
	},
	
	onActionComplete: function( form, action){

		obj = Ext.decode( action.response.responseText );
        if(obj.data && obj.data.id){
			this.setHiddenField('id',obj.data.id);
        }
		
		if( App.handleResponse)
			App.handleResponse(action.response);
		
		this.showResponseMessage(obj);
		
		this.fireEvent('saved');
	},
	setHiddenField: function(name,value){
		idF = this.getEl().select('[name="'+name+'"]');
		if (idF.getCount()) {
			idField = idF.item(0);
			idField.dom.value = value;
		}else {
			this.getEl().createChild('<input type="hidden" name="' + name + '" value="' + value + '" />');
		}
	},
	
	onBeforeAction: function (form,actions){
		form.getEl().select('.'+this.errorLabelCls ).remove();
	},
	
	onActionFailed: function( form, action){
		obj = Ext.decode(action.response.responseText);
		
		for( field in obj.verrors ){
			this.markInvalidField( form.getEl(), field, eval( 'obj.verrors.'+field ) );
		}
		if(App.handleResponse)
			App.handleResponse(action.response);
			
		this.showResponseMessage(obj);			
	},
	findInput:function(fieldName){
		patt = '[name="'+fieldName+'"]';
		field = this.getEl().select(patt).item(0);
				
        if( !field ){
            if( console ){
                console.log('nie znaleziono pola: '+fieldName);
            }
            return null;
        }				
		return field.dom;
	},
	markInvalidField: function ( form, fieldName, msg ){
		
		field = form.select('[name="'+fieldName+'"]').item(0);
		
		if( !field ){
		  if(console) console.log('Pole ' + fieldName + ' nie istnieje');
		}
		 
		cell = form.select('[name="'+fieldName+'"]').item(0).findParent('td');
		if( !cell )
			cell = form.select('[name="'+fieldName+'"]').item(0).findParent('div');

		//if( field.dom.type!='radio' )
			field.addClass(this.errorFieldCls);
		if( field.dom.type=='checkbox' ) Ext.fly(cell).addClass(this.errorContainerCls);

		//Ext.fly(cell).addClass(this.errorContainerCls);
	    
	    
		spn = Ext.fly(cell).createChild({
			tag: 'span',
			cls: this.errorLabelCls,
			html: ' '+msg
		});
		spn.setStyle({
			'opacity':0
		});

		spn.animate(
			    // animation control object
			    {
			        opacity: {to: 1, from: 0}
			    },
			    3,      // animation duration
			    null,      // callback
			    null, // easing method
			    'run'      // animation type ('run','color','motion','scroll')    
			);

		
	},
	clearInvalidMessage:function(form,fieldName){
        var field = form.select('[name="'+fieldName+'"]' ).item(0);
        
        field.removeClass(this.errorFieldCls);
        
        if( field ){
            try{
                field.next('.'+this.errorLabelCls).remove();
            }catch(e){}
        } 
        	    
	},
	applyInputHelps:function(elem){
	    try{
	      Ext.get(elem).select('input').each(function(el){
	          if( el instanceof Ext.Element ){
				var content = el.next('.input-help');
                if (content) {
                    new Ext.ToolTip({
						target: Ext.get(el),
						trackMouse: true,
						anchor:'left',
						autoShow: true,
					    showDelay: 10,
					    contentEl: Ext.get(content)
					});
				}      
		     }
	      });
		}catch(e){}
	},
	showResponseMessage:function(jsonObj){
		
		var title;
		
		if( jsonObj.success ){
			title = "Operacja zakończona powodzeniem";	
		}else{
			title = "Błąd";
			if( jsonObj.type = 'validation' ) return;
		}
		
		
			 
		this.messBox = $('body').append('<div class="mbox" title="'+title+'">'+jsonObj.msg+'</div>');
		
		
		$('.mbox').dialog({
			close: function(event, ui){
				$(this).dialog('destroy');
			},
			buttons:{
				'OK':function(){ $(this).dialog('close'); }
			}
		});


		
	}
});

