MySlide = new Class({
    
    Extends : Fx.Slide,

    initialize: function(element, options){

        this.addEvent('complete', function(){
            
			this.open = (this.wrapper['offset' + this.layout.capitalize()] != 0);

            if ( this.open == false ){
                element.set('html', '');
                element.setStyle('marginTop', 0);
            }
        
            var wrapperPai = this.wrapper.getParent('div.wrapper');
            if( wrapperPai != null )
            {   
                var tamPai = wrapperPai.getStyle('height').toInt();
                
                var ex = new Fx.Morph( wrapperPai, {duration: 'short', transition: Fx.Transitions.Sine.easeOut});
                
                var tam2 = ( this.isClosed( ) ) ? ( this.element.getStyle('marginTop').toInt() ) : ( this.element.getStyle('height').toInt() );

                ex.start({
                    'height': tamPai + ( tam2 ) + 'px',
                    'width': wrapperPai.getStyle('width')
                });
                
            }

            new Fx.Scroll(window).toElement(this.element);
            
			if (this.open && Browser.Engine.webkit419) this.element.dispose().inject(this.wrapper);

		}, true);

        //Se possuir a classe open_slide tras o slide aberto, senao tras fechado por default
        this.parent(element, options);
	    ( element.hasClass('open_slide')) ? this.show() : this.hide();
	},

    //Funcao criada para verificar se o slide encontra-se aberto ou fechado no click
    isClosed: function( ) {
        return this.layout? this.wrapper['offset' + this.layout.capitalize()] == 0: false;
    },

    RecalcHeight: function( idiv )
    {
        // Procura o wrapper de fora do slide
        while( idiv )
        {
            if( idiv.className && idiv.hasClass('conteudo') )
                break;
            idiv = idiv.parentNode;
        }

        if( !idiv )
            return;

		height = idiv.offsetHeight;

        // Atualiza a altura da div
		idiv = idiv.getParent('.wrapper');

        // Atualiza a altura da div
        if( idiv )
			idiv.setStyle( 'height', height );

    }
});


RecalcHeight = new Class({
    
    initialize: function( idiv )
    {
        // Procura o wrapper de fora do slide
        while( idiv )
        {
            if( idiv.className && idiv.hasClass('conteudo') )
                break;
            idiv = idiv.parentNode;
        }

        if( !idiv )
            return;

		height = idiv.offsetHeight;

        // Atualiza a altura da div
		idiv = idiv.getParent('.wrapper');

        // Atualiza a altura da div
        if( idiv )
			idiv.setStyle( 'height', height );

    }
});

InitSlides = new Class({
	edit_callbacks: [],
    initialize: function( links, targets )
    {
    	this.botoes = links;
    	this.conteudos = targets;

        var botoes = $$(links);
        var conteudos = $$(targets);
        
        botoes.each( function(botao, i )
        {
            this.eventoClick( botao, conteudos[i] );
        },this);
    },

    eventoClick: function ( botao, div )
    {
        var myVerticalSlide = new MySlide( div, {mode: 'vertical'});
        botao.addEvent('click', function(e){
            if(window.location.hostname=='localhost'){
                div.parentNode.setStyle('overflow', '')
            }
            if ( myVerticalSlide.isClosed() )
                Loading.apply();

            setTimeout( function(){ new InitSlides().call_edit( botao, div, myVerticalSlide ) },'500');
        });
    },
    add_edit_callback: function(funcao){
        if(!InitSlides.prototype.edit_callbacks.contains(funcao)){
            InitSlides.prototype.edit_callbacks.push(funcao);
        }
    },
    call_edit: function( botao, div, elemSlide ){

        var delay = '';
        var explode = (div.get('id')) ? div.get('id').split("_") :null;
        var id=explode[1];
        div.getProperty("class").split(' ').each( function( classe ){
            if(classe.match(/^SlideDelay(\[.+\])$/))
                delay = eval(classe.match(/^SlideDelay(\[.+\])$/)[1]);
            else
                delay = '200';
        });

       new SlideLabel().trocar( botao, elemSlide.isClosed() );

        if ( elemSlide.isClosed() === true )
        {
            new Util().callHTML(
                site_url + '/admin/'+controller+'/newElement/' + ( (explode[1])?explode[1]:null ), function( response ){
                div.set('html', response );
				Form.init();
                new Util().LimitChars();
                
                setTimeout( function( ){
                   Loading.remove();
                }, delay/2 + delay/3 + delay/4);

               //Form.init();
                setTimeout(function(){
                    elemSlide.toggle();
                    InitSlides.prototype.edit_callbacks.each(function(funcao){
                        funcao(controller, id);
                    })
                }, delay);
            });
        }else{
            div.set('html', '' );
            Loading.remove();
            elemSlide.toggle();
        }
    },
    
    returnAjax: function( id )
    {
        var myVerticalSlide = new MySlide( $('elementoConteudo_'+id), {mode: 'vertical'});
        $( 'botao_elementoConteudo' + id ).addEvent('click', function(e){
            new SlideLabel().trocar( $('botao_elementoConteudo'+id), myVerticalSlide.isClosed() );
            myVerticalSlide.toggle();
        });
    }
});

SlideLabel = new Class({

    trocar: function ( botao, status )
    {
        var elem = $( botao );
        var tag = elem.get('tag');
        var text = elem.get('text');

        if ( tag == 'a' || tag == 'div' || tag == 'span' )
        {
            if ( text == 'Adicionar' && status )
			{
				$( botao ).set('text', 'Fechar');
			}
            else if ( text == 'Fechar' && !status )
            {
				$( botao ).set('text', 'Adicionar');
			}
			if ( text == 'Editar' && status )
			{
				$( botao ).set('text', 'Cancelar');
				$( botao ).removeClass('bts');
				$( botao ).addClass('bts_cancel');
			}
            else if ( text == 'Cancelar' && !status )
            {
				$( botao ).set('text', 'Editar');
				$( botao ).removeClass('bts_cancel');
				$( botao ).addClass('bts');
			}      
        }
    }
});

var Form = {
	init: function()
	{
		$$('form.formAjax').each(function(form, i){
			AIM.submit(form, {
                onComplete: function(felm, config, resHtml, resText)
                {
                	($('ajaxDebug')) ? $('ajaxDebug').set('html', resHtml) :null;
                	
                	var result = JSON.decode( resText.replace( /\[\&([^\&]+[^\]]*)\&\]/gi, '<$1>' ) );
		        	
		        	Form.validate(result.errors, result.id, result.isNew);
		        	
		        	if( result.isOk )
			        {
						if ( result.isNew )
						{
							felm.reset();
							
							var newDiv = new Element("div");
							newDiv.addClass('listaElemento');
							newDiv.set('id','listaElemento_'+result.id);
							newDiv.set('html',result.html);
							
							// Setando a classe que cria
							newDiv.addClass('listaElementoNovo');
							
							// Injetando a nova div na div listaNovos, que 
							// ficam os elementos novos  
							newDiv.inject($('listaNovos'));
							
							var DivId = 'elementoConteudo'+result.id;
							new InitSlides().eventoClick( $('botao_elementoConteudo' + result.id), $('elementoConteudo_' + result.id) );
							
							$('botaoNovoElemento').fireEvent('click', $('botaoNovoElemento'), 50 );
							
							$$('a.previews').each(function(el){
						        Util.previewToolTip(el);
						    });			
							
						}
						else
						{						
							var DivId = felm.getParent('div.conteudo').get('id');
									
							//alert(result.html);
							$('listaElemento_'+result.id).set('html',result.html);
							
							//Isso reinstacia o preview de gráficos
							if($('preview'+result.id))
								Util.previewToolTip($('preview'+result.id));
							
							// Quando quiser que o elemento venha aberto adiciona essa classe
							// No caso abaixo, adicionamos ela aberta, e logo apos
							// o evento FireEvent ira fecha-la 
							//$('elementoConteudo'+result.id).addClass('open_slide');
							
							// Esse cara adiciona o evento ao novo elemento inserido
                            //new Util();
							//new InitSlides().returnAjax(result.id);

                            new InitSlides().eventoClick( $('botao_elementoConteudo' + result.id), $('elementoConteudo_' + result.id) );
                            
                            
							// Esse bloco faz o div editado ser carregado aberto, simulando o click
							//$('botao_' + DivId).fireEvent('click', $('botao_' + DivId), 100 );
							 
						}
						Form.init();
			        }			        
			        
                }
            });
		});
	},
	
	validate: function(errors, id, isNew, campo)
	{
		campo = campo==null ?'' :campo+'.';
		
		id = id==null || isNew.toString()=='true' ?'0' :id;
		
		//alert(id);
		
		for ( err in errors )
		{
		
			if ( Form.is_object(errors[err]) )
			{
				Form.validate(errors[err], id, isNew, campo+err);
			}
			else
			{
				if ( !Form.is_bool(errors[err]) )
				{
					var _errors = errors[err];
					var _campo = campo+err+'.';
					
					total = _errors.length;

					for ( var i = 0; i < total; i++ )
					{
						Form.validate(_errors[i], id, isNew, _campo+i);
					}					
					
				}
				else
				{				
					if($(campo+err+id))
					{												
						var field = $(campo+err+id);						
						
						field.style.border = errors[err] ?'1px solid #ff0000' :'';
						
						//alert(field.id);
					}	
					
				}
				
			}
		}
	},
	
	is_object: function ( mixed_var ){
	    // http://kevin.vanzonneveld.net
	    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	    // +   improved by: Legaev Andrey
	    // +   improved by: Michael White (http://getsprink.com)
	    // *     example 1: is_object('23');
	    // *     returns 1: false
	    // *     example 2: is_object({foo: 'bar'});
	    // *     returns 2: true
	    // *     example 3: is_object(null);
	    // *     returns 3: false
	 
	    if(mixed_var instanceof Array) {
	        return false;
	    } else {
	        return (mixed_var !== null) && (typeof( mixed_var ) == 'object');
	    }
	},
	
	is_bool: function (mixed_var)
	{
	    // http://kevin.vanzonneveld.net
	    // +   original by: Onno Marsman
	    // *     example 1: is_bool(false);
	    // *     returns 1: true
	    // *     example 2: is_bool(0);
	    // *     returns 2: false
	 
	    return (typeof mixed_var == 'boolean');
	}
};

