/********************************************************************************/
/*                                                                              */
/* Plataforma MurciaEduca.  Version 6.09.03-17 - Region de Murcia - Espana      */
/* Distribucion de e-ducativa Open College                                      */
/* Copyright (c) 2007-2008 de e-ducativa Educación Virtual S.A.                 */
/*                                                                              */
/********************************************************************************/
Educativa.Control.Forms = {};
Educativa.Control.Form = Class.create(Educativa.Control, {
    initialize : function($super, form)
    {
        if ( ! Educativa.Control.Forms[ form.id ] )
        {
            $super( form.id );
            this.form = form;
            this.funciones_validacion = new Array();

            // form indicator
            var submit = this.element.select( 'div.submit' ).first();

            if ( submit )
            {
                this.indicator = new Element('div',
                    { className : 'ajax_indicator form_indicator' } );

                Position.clone( submit, this.indicator, {
                    setWidth: false, setHeight: false, setLeft: false, setTop: false
                });
                submit.appendChild( this.indicator ).hide();
            }

            // no uso observe() porque es necesario q se ejecute lo mas pronto posible
            this.element.onsubmit = this.submit.bindAsEventListener(this);

    		Educativa.Control.Forms[ this.form.id ] = this;
            var invalid = this.element.select('.invalido .control').first();
            if ( invalid ) {
                try { invalid.focus() }
                catch(e){};
            }
            else if (this.form.auto_focus )
                try { this.element.focusFirstElement() }
                catch(e){};

        }
    },
    canceled : false,
    submit : function(e)
    {
        if ( ! this.canceled && ! this.validar() )
        {
            if ( e ) Event.stop(e);
            this.fire('onInvalid');
        }
        else if ( this.form.ajax )
        {
            var form = this.form;
            if ( e ) Event.stop(e);
            $( form.id ).request({
                parameters : { wPartial : 1},
                onCreate   : Form.disable.bind(Form, this.element ),
                onComplete : Form.enable.bind(Form, this.element ),
                onSuccess : function(tr)
                {
                    var result = tr.responseText.evalJSON();
                    if ( result.state == 1 ){
                        new Educativa.Alert( {
                            type : 'info',
                            text : 'Se guardo ok'
                        } );
                        $( form.id ).reset();
                        if (tinyMCE) form.controles().each(function(f){
                            if (f.clase == 'RichText' )
                            tinyMCE.updateContent(f.id);
                        })
                    }

                }
            });
        }
        else
        {
            if ( !e ) this.element.submit();
            //Se pregunta por el boton submit comun
            if($('wOk')){
                $('wOk').addClassName( 'inputSubmitDisabled');
            }
            //Se pregunta por el boton submit "guardar y seguir" de la seccion presentacion(Backend)
            if ($('wOkEdit')){
                $('wOkEdit').addClassName( 'inputSubmitDisabled');
            }
            //Se pregunta por el boton submit de la seccion importacion
            if($('wCancel')){
                $('wCancel').addClassName( 'inputSubmitDisabled');
            }

            if (this.indicator) this.indicator.show();
            Form.disable.delay(0, this.element );

        }

    },
    controles : function()
    {
        return this.element
                   .select('*')
                   .findAll(function(e){return e['E']})
                   .invoke('E')
                   .reject( Object.isUndefined )
    },
    validar_elemento : function(element){
        return ! element.isVisible || ! element.isVisible() || element.validar();
    },
    validar_elementos : function( elementos ){
        var result = elementos.partition( this.validar_elemento.bind(this) );
        result[0].each(function(e){ if ( e.valido   ) e.valido()   });
        result[1].each(function(e){ if ( e.invalido ) e.invalido() });
        return result;
    },
	validar : function ()
	{
	    /* Lista con dos arrays, el primero de elementos que validaron
	       el segundo con los elementos que no validaron */
        var result = this.validar_elementos( this.controles() );

        // dejo seteada la propiedad status como resultado de la validacion
        // true : hay errores, false : correcto
        this.status = result[1].length > 0;

        if ( this.status )
        {
			this.invalido();
			result[1].first().select();
			return false;
		}
		else
        {
            // verifico las funciones personalizadas de validacion
            var validacion_extra = true;
            this.funciones_validacion.each(function(f){
                validacion_extra = f() && validacion_extra;
            });
            if (validacion_extra) return this.valido();

            this.invalido();
            return false;
		}

	},
	invalido : function()
	{
	    if (this.form.invalid_text)
            alert( this.form.invalid_text.stripTags() );
        return false;
    },
    valido : function()
    {
        return ! this.form.confirm || confirm(this.form.confirm);
    },
    // agrega una funcion javascript personalizada
    agregar_validacion : function (func)
    {
        this.funciones_validacion.push(func.bind(this));
    }

});
Educativa.Control.Form.newInput = function(options) {
	var clase = Educativa.Control[ options.clase ]
	    ? 'Educativa.Control.' + options.clase
	    : 'Educativa.Control.InputBase';
	return object = eval('(new ' + clase + '( options ) )');
};




/* Validaciones en javascript
 *
 */
Educativa.Control.Base = Class.create(Educativa.Control, {
	initialize : function($super, options ){
	    Object.extend( this, options);

	    if ( options.element ){
	        this.id = this.element.id;
	        this.name = this.element.name;
	    }

	    $super( this.id );

	    this.element = this.element || $( this.name + '_0');


        this._validacion_especiales = [];

	    try {
    	    this.form = this.element.ancestors().find(function(e){ return e.tagName.toLowerCase() == 'form'});
    	    this.line = this.element.ancestors().find(function(e){ return e.hasClassName('line') } );
        } catch(e){};

        if ( this.element ) ['blur', 'focus'].each(
            function(f){this.element.observe(f, this[f].bindAsEventListener(this) )}.bind(this)
        )

    	if( options.tooltip )
        	this.tooltip = new Educativa.Tooltip({
    	        trigger : $(options.tooltip + 'bt'),
    	        html    : $(options.tooltip + 'tt').remove().innerHTML,
    	        canFixed: true
            }).hide();
	},
	editable : function(){
	    return this.clase != 'LabelText';
	},
	isVisible : function(e){
	    return this.element.visible()
	           && ! this.element.ancestors().find(function(e){return ! e.visible()
	                // y no es del accordion, hack
	                && ! e.hasClassName('contents') })
    },
	focus : function (e){
	    if ( !this.visible() ) return ;
    	$(this.id).addClassName( 'focus');
    	try { $(this.id).select() } catch(e){};
    },
	blur  : function (e){
	    if ( !this.visible() ) return ;
    	$(this.id).removeClassName( 'focus' );
    },
	visible : function(){
		return this.element ? this.element.type != 'hidden' : false;
	},
	select : function (){
		try {
			this.element.focus();
			this.element.select();
		} catch(e){};
	},
	invalido: function(){
        var line = this.line;
		this.element.removeClassName('valido').addClassName('invalido');
		if ( line ) {
			line.removeClassName('valido').addClassName('invalido');
			if ( ! this.help ) return ;
			if ( ! this.div_help ){
				this.div_help = $(this.help_id)
				    ? $(this.help_id)
				    : line.appendChild(new Element( 'div', { id : this.help_id , className : 'help'} ))
				          .hide().update(this.help);
			}
			this.div_help.show() ;
		}
	},
	valido: function(){
	    var line = this.line;
        this.element.removeClassName('invalido').addClassName('valido');
		if ( line ) {
			line.addClassName('valido').removeClassName('invalido');
			if (this.div_help) this.div_help.hide();
		}
	},
	add_validacion : function(fn){
        this._validacion_especiales.push( fn.bind(this) );
	},
	validar_especial : function(){
	    if ( this._validacion_especiales.length == 0 )
            return true;

        return this._validacion_especiales
		   .invoke('call')
		   .findAll(function(valida){ return valida == false; })
           .length == 0;
	},
	validar : function() {
		var err = 0;
		var valida = true;
		if ( ! this.element.disabled && (this.required || this.tiene_valor()) ){
			if (valida && !this.validar_requerido()   ){err = 1; valida = false; }
			if (valida && !this.valida_tipo_dato()    ){err = 2; valida = false; }
			if (valida && !this.validar_length()      ){err = 3; valida = false; }
			if (valida && !this.validar_especial()    ){err = 4; valida = false; }
		}
		this.err = err;
		return valida ;
	},
	longitud : function (){
		return this.value().length;
	},
	tiene_valor : function (){
		return this.value() ? !! this.value().length : 0;
	},
	validar_length : function() {
		return (Object.isUndefined(this.minlength) || !this.minlength || this.longitud() >= this.minlength)
 		    && (Object.isUndefined(this.maxlength) || this.maxlength == 0 || this.longitud() <= this.maxlength)
	},
	valida_tipo_dato : function(){ return true },
	validar_requerido : function(){
		return !(this.required && ! this.tiene_valor() );
	},
	value : function (){
		return this.element.value;
	},
	set_value : function(value){
	    this.element.value = value;
    },
    enable : function(){
        try{ this.element.enable() } catch(e){};
        var arr = this.element.select('input,select,textarea');
        if (arr) arr.invoke('enable');
    },
    disable : function(){
        try{ this.element.disable() } catch(e){};
        var arr = this.element.select('input,select,textarea');
        if (arr) arr.invoke('disable');

    }
});


Educativa.Control.InputBase = Class.create(Educativa.Control.Base, {});


Educativa.Control.Submit = Class.create(Educativa.Control.Base, {
    focus : function(){ }
});

Educativa.Control.Text = Class.create(Educativa.Control.Base, {
	initialize : function($super, options ){
	    $super(options);
	    if( options.prompt ) {

	        this.set_prompt( options.prompt );
	    }


	},

    _prepareValue : function() {
        if ( this.element.readAttribute( 'prompt' ) )
            this.element.value = ''
    },
	_initPrompt : function(){
	    this.form.observe('submit', this._prepareValue.bind(this) );
	},
	set_prompt : function(text) {
	    var e = this.element;
	    if( null !== text ) {

	        $ready( this._initPrompt.bind(this) );

	        this.prompt = text;
	        if( e.value == '' ) {
	            e.writeAttribute( 'prompt', true );
	        }
	        else {
	            e.writeAttribute( 'prompt', false);
	        }

	        e.observe( 'focus', function(){
                if ( e.readAttribute( 'prompt' ) ) {
	                this.element.value='';
	                this.element.removeClassName('showPrompt');
	            }

	            }.bind(this)
	        ).observe( 'blur', function(){
	            if ( e.readAttribute( 'prompt' ) ) {
	                this.element.value=this.prompt;
	                this.element.addClassName('showPrompt');
	            }
	        }.bind(this)
	        ).observe( 'change', function(){
	            this.element.writeAttribute( 'prompt', this.element.value == '' );
	        }.bind(this)
	        )
	    }
	},
	_promptChange : function(){
        var e = this.element;
        if (e.value == '' || e.value == this.prompt ){
            e.addClassName('noValue');
            e.value = this.prompt;
        }
        else {
            e.addClassName('noValue');
        }

    },
	valida_tipo_dato : function( ){
        var validacion = Educativa.Control.Text.Validaciones[this.tipo_dato]
        return ! validacion || validacion( this.value() )
	},
	tiene_valor : function ($super){
		// tiene valor si no hay todos blancos y length > 0
		return ! this.element.readAttribute('prompt')
		  && (!! this.value().length)
		  && ! this.value().match( /^\s+$/ );
	}
});
Educativa.Control.Text.Validaciones = {
    simple  : function(v){return !v.match(/\r?\n/m)                },
    usuario : function(v){return  v.match(/^[\w\.]+$/)             },
    id      : function(v){return !v.match(/\W/)                    },
    lista_email : function(v){return  v.match(/@/)     },
    email   : function(v){return  v.match(/@/)     },
    uri     : function(v){return  Educativa.Utils.is_uri( v ) },
    sitio   : function(v){return  v.match(/^\[CD\]/i) || Educativa.Utils.is_uri( v )}
};

Educativa.Control.Number = Class.create(Educativa.Control.Base, {
	valida_tipo_dato : function(){
        return this.value().match(this.tipo_dato == 'entero' ? /^\d+$/ : /^([\d\.,-]+)$/);
	},
	tiene_valor : function (){
		// tiene valor si no hay todos blancos y length > 0
		return this.value().length && ! this.value().match( /^\s+$/ );
	},
	longitud : function (){
		return this.value();
	}
} );

Educativa.Control.Password = Class.create(Educativa.Control.Text, {
	valida_tipo_dato : function(){ return this.value().match(/^[\w\.]+$/) }
} );


Educativa.Control.RichText = Class.create(Educativa.Control.Base, {
	visible : function(){ return false },
	value   : function(){
	    if(self.tinyMCE && self.tinyMCE != null ) tinyMCE.triggerSave();

        var value = this.element.value;
        return value.match(/\<(img|object)/i) ? value : value.unescapeHTML();
	},
    valida_tipo_dato : function($super){
        v = $super();
        if ( v && this.validation_re ){
            if(self.tinyMCE && self.tinyMCE != null ) tinyMCE.triggerSave();
            var re = new RegExp(this.validation_re,'ig');
            v = re.test( this.element.value );
        }
        return v;
    },
	isVisible   : function() {
	    return true
    },
	tiene_valor : function (){

		// tiene valor si no hay todos blancos y length > 0
		return this.value().length && ! this.value().match( /^(&nbsp;|[\s\n\r])*$/ );
	},
	focus : function(){
        tinyMCE.execCommand('mceFocus', false, this.id);
	},
	select : function (){
	    tinyMCE.execCommand('mceFocus', false, this.id);
	}
});

Educativa.Control.Select = Class.create(Educativa.Control.Base, {
	tiene_valor : function (){
		return this.value().length && ! this.value().match( /^\s+$/ );
	}
});

Educativa.Control.RadioGroup = Class.create(Educativa.Control.Base, {
	options : function()
	{
	    return this.element.select('[type="radio"]')
	},
	value : function (){
        var it = this.options().find(function(e){return e.checked });
        return it ? it.value : null;
	},
	visible: function(){ return false }
});

Educativa.Control.CheckGroup = Class.create(Educativa.Control.Base, {
	value : function(){
        return this.element.select('[type="checkbox"]')
            .findAll(function(e){return e.checked })
            .map(function(e){ return e.value} )
	},
	visible: function(){ return false }
});

Educativa.Control.SelectMultiple = Class.create(Educativa.Control.Base, {
	value : function(){
		return $F(this.name);
	}
});

Educativa.Control.File = Class.create(Educativa.Control.Base, {
    valida_tipo_dato : function(){
		var val = this.value().toLowerCase();


		if( val.match(';')  ) return false;

		function iterator (ext){
            return val.match( '\.' + ext.toLowerCase() + '$' );
        }
		if ( this.permitir.length > 0 ){
		    return this.permitir.select( iterator ).length;
		} else if ( this.denegar.length > 0 ){
		    return this.denegar.reject( iterator ).length;
        } else {
            return true;
        }
	},
    validar_length : function() {return true}
});



Educativa.Control.MantenerQuitarArchivo = Class.create(Educativa.Control.RadioGroup,
{
    initialize : function($super, options )
    {
        $super(options);
        this.file = $( options.file ).E();
        var opt = this.options().invoke('observe','click',
            this._requerir_file.bindAsEventListener(this));

        var a = this.element.select('a').first();
        if (a) a.observe('click', this.previsualizar.bindAsEventListener(this));

        if ( opt.length > 0)
        {
            this.file.disable();
            this.file.required = false
        }
        else
        {
            this.file.enable();
        }

    },
    previsualizar : function(event)
    {
        event.stop();
        var ele = event.element();
        var href = ele.href;
        Educativa.Popup.open( {
            url      : href,
            name     : this.id,
            width    : 640,
            height   : 400,
            toolbar  : false,
            depend   : true
        } );


    },
    _requerir_file : function(event)
    {
        (this.file.required = event.element().value == 2)
            ? this.file.enable()
            : this.file.disable();
    },

    value : function ($super){
        return this.options().length > 0 ? $super() : 2;
	},
	tiene_valor : function ($super){
        return this.options().length > 0 ? $super() : 2;
	},

	validar : function($super) {
        if ( ("input[name='" + this.id + "']").length == 1
            || ("input[name='" + this.id + "'][checked='checked'][value='2']").length == 1 ){
            return this.file.validar();
        }else{
            return $super();
    	}
    }
});

Educativa.Control.DynForm = Class.create(Educativa.Control.Base, {
    initialize : function($super, options )
    {
        $super(options);
        var t = this;
        DynForm.instance.onQuestionAdded = function() {
            t.valido();
        };
    },
	validar : function ($super){
        if ( ql.toFormInput(this.form.id, "encuestas_preguntas") )
            return true;
		return false;
	}
});

// Parametros obligatorios:
//    trigger    : 'agregar_curso_button', //id del elemento que dispara la ventana
//    container  : 'cursos_rows',          // id del elemento en donde se insertan
//    ajax_url   : '?wAccion=ajax_cursos_list&id_encuesta=$e_id' /url de donde se toman los elementos
// Parametros opcionales:
//    page_limit : 10,
//    className  : 'list_select_dialog',
Educativa.Control.ListSelectDialog = Class.create( Educativa.ListSelectDialog ,{

    initialize : function( $super, args) {

        var options = {
            container : null,
            className : 'ListSelectDialog',
            void_list_message : Educativa.Dict.NO_EXISTEN_CURSOS_DISPONIBLES.capitalize(),
            offsetLeft: $(args.trigger).getWidth()+10,
            offsetTop : -80,
            title     : 'asociar'
        };

        Object.extend( options, args); //para pisar los defaults

        $super( options );

    },

    asociar_item: function(arg){
        var obj = arg.item;

        /////////////////////////////////
        // boton para desasociar items //
        /////////////////////////////////
        var d_button = new Element('a',{ className: 'list_select_delete_button' }).update('');
        //activamos o desactivamos la posibilidad de desasociar el curso
        if( obj.realizaciones ) d_button.addClassName('list_select_delete_button_desactivado');
        else                  d_button.addClassName('list_select_delete_button_activo');

        ///////////////////////////////////////////////
        // coloreamos de acuerdo a si es par o impar //
        ///////////////////////////////////////////////
        var index = arg.index;  // indice de la fila
        if( index == null ){
            index = $A(this.lista).findAll(function(obj){ return obj.asociado == 1 }).size();
        }
        var attrs = { className: ( (index % 2) ?'': 'fila_impar')  };

        ///////////////////////////////
        // creamos la fila a agregar //
        ///////////////////////////////
        var row = new Element('tr');

        for( var i=0; i < this.headers.length ; ++i){
            var  column_def =  this.headers[i];
            row.insert(
                new Element('td', attrs).insert(
                    new Element('span').update(obj[column_def.key])
                )
            );
        }

        row.insert(
                new Element('td', attrs).insert(
                  new Element('div',{className: 'list_select_delete_button_c' }).update(' ')
                      .insert( d_button)
                )
        );

        obj.imagen = row;

        $(this.container).insert(row);


        obj.asociado = 1;
        this.draw_items_list();

        //cerramos la ventana en caso de que no queden mas cursos
        if(  $A(this.lista).findAll(function(obj){ return obj.asociado == 0 }).size() == 0 ){
            this.menu.hide();
        }

        //evento de desasociar curso
        if( ! obj.realizaciones ) d_button.observe('click', this.desasociar_item.bind(this,{item: obj}) );

    },

    desasociar_item: function(arg){
        var obj = arg.item;
        obj.asociado = 0;
        obj.imagen.remove();
        this.draw_items_list();
    },

    toFormInput: function(formId, inputName){
        var frm = $(formId);
        $$('.'+inputName+'_class').each(function(e){
            e.remove();
        });
        $A(this.lista).findAll(function(obj){ return obj.asociado == 1 }).each( function (obj) {
            frm.insert(new Element('input',{
                className: inputName+'_class',
                name  : inputName,
                value : Object.toJSON({
                    id: obj.id
                }),
                type  : 'hidden'
            }));
        });
        return true;

    }

});


// Parametros obligatorios:
//    trigger    : 'agregar_curso_button', //id del elemento que dispara la ventana
//    container  : 'cursos_rows',          // id del elemento en donde se insertan
//    ajax_url   : '?wAccion=ajax_cursos_list&id_encuesta=$e_id' /url de donde se toman los elementos
// Parametros opcionales:
//    page_limit : 10,
//    className  : 'list_select_dialog',
Educativa.Control.DoubleList = Class.create({

    initialize : function( args ) {
        var cont = $(args.container);

        cont.update( );
        cont.insert( new Element('div', {'id': args.id + '_left',
                                         'class' : 'double_list_container'}
        ));
        cont.insert( this._makeButtons(args.urlImg) );
        cont.insert( new Element('div', {'id': args.id ,
                                         'class' : 'double_list_container'}
        ));

        this.list_left = new DynListControl({
            target: args.id + '_left',
            name: args.id + '_left',
            onDblClick : this.onLeftItemClick.bind(this),
            double_control : this,
            sort: true,
            label: Educativa.Dict.DISPONIBLES.capitalize()
        });
        this.list_right = new DynListControl({
            target: args.id + '',
            name: args.id + '',
            onDblClick : this.onRightItemClick.bind(this),
            double_control : this,
            sort: true,
            label: Educativa.Dict.SELECCIONADOS.capitalize()
        });

        this.list_right.addItem(args.selected);
        this.list_left.addItem(args.items);

        Event.observe(this.list_right.list_element, 'keydown',
            this.onRightListKeyDown.bindAsEventListener(this));
        Event.observe(this.list_left.list_element, 'keydown',
            this.onLeftListKeyDown.bindAsEventListener(this));

        this.onChange = args.onChange;

        $(args.id).educativa_control = this;
    },
    getSelected : function() {
        return this.list_right.items.map(function(itm){return itm.get('value')});
    },
    toRight : function ( itm ) {
        if (!itm) return;
        var newitem = itm.clone();
        this.list_right.addItem( newitem );
        this.list_left.selectRel(itm,1, true);
        this.list_left.removeItem(itm);
        this.list_right.selectItem( newitem );
        if (this.onChange) this.onChange(this);
    },
    toLeft : function ( itm ) {
        if (!itm) return;
        var newitem = itm.clone();
        this.list_left.addItem( newitem );
        this.list_right.selectRel(itm,1, true);
        this.list_right.removeItem(itm);
        this.list_left.selectItem( newitem );
        if (this.onChange) this.onChange(this);
    },
    onLeftItemClick : function (ev, itm) {
        this.toRight(itm);
    },
    onRightItemClick : function (ev, itm) {
        this.toLeft(itm);
    },
    onLeftBtnClick : function (ev) {
        var itm = this.list_right.getSelected();
        if (itm) this.toLeft( itm );
    },
    onRightBtnClick : function (ev) {
        var itm = this.list_left.getSelected();
        if (itm) this.toRight( itm );
    },
    onLeftListKeyDown : function (ev) {
        if (ev.keyCode == 39) { // right arrow
            this.toRight(this.list_left.itemSelected);
            return 0;
        } else if (ev.keyCode == 37 && this.list_right.itemSelected) { // left arrow
            this.toLeft(this.list_right.itemSelected);
            return 0;
        }
    },
    onRightListKeyDown : function (ev) {
        if (ev.keyCode == 37) { // left arrow
            this.toLeft(this.list_right.itemSelected);
            return 0;
        } else if (ev.keyCode == 39 && this.list_left.itemSelected) { // right arrow
            this.toRight(this.list_left.itemSelected);
            return 0;
        }
    },
    _makeButtons : function (url_img) {
        var cont = new Element('div', {'class' : 'dynlist_btn_container'});
        var btn_left = new Element('a', {'class' : 'dynlist_btn', href: 'javascript: void(0)'});
        var btn_right = new Element('a', {'class' : 'dynlist_btn', href: 'javascript: void(0)'});

        Event.observe(btn_right, 'click', this.onRightBtnClick.bindAsEventListener(this));
        Event.observe(btn_left, 'click', this.onLeftBtnClick.bindAsEventListener(this));

        btn_left.insert( new Element('img', {'src' : url_img + 'btn_left.gif'}) );
        btn_right.insert( new Element('img', {'src' : url_img + 'btn_right.gif'}) );
        cont.insert( btn_right );
        cont.insert( btn_left );

        return cont;
    }
});

