// JavaScript Document
window.addEvent('domready', function() {
	
	function var_dump(obj) {
        if(typeof obj == "object") {
          return "Type: "+typeof(obj)+((obj.constructor) ? "\nConstructor: "+obj.constructor : "")+"\nValue: " + obj;
        } else {
          return "Type: "+typeof(obj)+"\nValue: "+obj;
        }
     }//end function var_dump
	
    // Dar opacidad 0 y luego sacar el display none;
    if($chk($('formtips'))){
        $('formtips').set('opacity',0).show();
    }

    // Muestra el tip en base a "top" del elemento dado
    function mostrar_tip(el){        
        if(el.get('title') != null && el.get('title') != ""){
            $('formtips').setStyle('opacity',0).setStyle('top', el.getParent().getPosition('contenedor_cv').y);
            $$('#formtips p').set('html', el.get('title'));
            $('formtips').fade(1);
          //  el.removeProperty('title');
        }
    }
	
    // Oculta el tip
    function ocultar_tip(el){
        $('formtips').fade(0);
       // el.set('title',$$('#formtips p').get('html'));
    }
	
    //Desabilitado porque hacia que el tooltip aparezca en cualquier lado
	/*
	var primerTextInput = $('contenedor_gral').getElement('input[type=text]');
    if($chk(primerTextInput)){ //Hacer focus en el primer input si es de texto
        primerTextInput.select();
        mostrar_tip(primerTextInput);
    }*/
	
    $$('#form_cv input.text','#form_cv textarea','#form_cv select').addEvent('focus', function(event){
        // Esto agrega la clase "actual" a IE > 7 para que los input tengan efecto :focus
        mostrar_tip(this);
        if(Browser.Engine.trident && Browser.Engine.version >= 5){
            this.addClass('actual');
        }
    });
	
    $$('#form_cv input','#form_cv select','#form_cv textarea').addEvent('blur', function(event){
        ocultar_tip(this);
        if(Browser.Engine.trident && Browser.Engine.version >= 5){
            this.removeClass('actual');
        }
    });
	
    $$('li.combo','li.checkbox').addEvent('mouseenter', function(event){
        mostrar_tip(this);
    });
	
    $$('li.combo','li.checkbox').addEvent('mouseleave', function(event){
        ocultar_tip(this);
    });
	
    //Seleccionar el primer input y mostrar tip al cargar la pagina
    //$('form_cv').getElement('input').focus();
    //mostrar_tip($('form_cv').getElement('input'))

    if($chk($('form_cv'))){
        new FormCheck('form_cv');
    }
    
    if($chk($('username'))){
        $('username').addEvent('blur', function(event){

            var ajax = new Request({
                method: 'get',
                url: "/aplicantes/client.ngmf?op=checkUsername&username="+$('username').value,
                onRequest: function(){},
                onFailure: function(){},
                onSuccess: function(texto, xmlrespuesta) {
                    if(texto == 'ok'){
                        $('username').getParent().removeClass('requerido');
                        $('username').getParent().getElement('label').removeClass('requerido');
                        var aux = $('username').title;
                        $('username').title = $('username').getAttribute('rel');
                        $('username').setAttribute('rel',aux);

                    }else{
                        var aux = $('username').title;
                        $('username').title = $('username').getAttribute('rel');
                        $('username').setAttribute('rel',aux);
                        $('username').getParent().addClass('requerido');
                        $('username').getParent().getElement('label').addClass('requerido');
                    }
                }
            }).send();
        });
    }

    if($chk($('nacionalidad'))){
        $('nacionalidad').addEvent('change', function(event){

            var ajax = new Request({
                method: 'get',
                url: "/aplicantes/client.ngmf?op=tipodoc&idpais="+$('nacionalidad').value,
                onRequest: function(){
                    $('tipodocumento').setAttribute('disabled', 'disabled');
                    $('tipodocumento').getParent().addClass('cargando');
                },
                onFailure: function(){},
                onSuccess: function(texto, xmlrespuesta) {
                    $('tipodocumento').innerHTML = texto;
                    $('tipodocumento').getParent().removeClass('cargando');
                    $('tipodocumento').removeAttribute('disabled');
                }
            }).send();
        });
    }

    if($chk($('paisDomicilio'))){
        $('paisDomicilio').addEvent('change', function(event){

            var ajax = new Request({
                method: 'get',
                url: "/aplicantes/client.ngmf?op=provincias&idpais="+$('paisDomicilio').value,
                onRequest: function(){
                    $('provincia').setAttribute('disabled', 'disabled');
                    $('provincia').getParent().addClass('cargando');
                },
                onFailure: function(){},
                onSuccess: function(texto, xmlrespuesta) {
                    $('provincia').innerHTML = texto;
                    $('provincia').getParent().removeClass('cargando');
                    $('provincia').removeAttribute('disabled');
                }
            }).send();
        });
    }
    
    if($chk($('ins_institucion'))){
        $('ins_institucion').addEvent('change', function(event){
            if($('ins_institucion').value == 0){
                $('otraInstitucion').focus();
                $('otraInstitucion').removeClass('oculto');
                $('otraInstitucion').addClass("validate['required']");
            }else{
                $('otraInstitucion').addClass('oculto');
                $('otraInstitucion').removeClass("validate['required']");
            }
        });
    }

        if($chk($('conoceExtras'))){
        $('form_cv').getElements('input[name=conoce]').addEvent('change', function(event){
            if(this.value == 1){
                $('conoceExtras').focus();
                $('conoceExtras').removeClass('oculto');
            }else{
                $('conoceExtras').addClass('oculto');
                $('conoceExtras').removeClass("validate['required']");
            }
        });
    }

    if($chk($('paisEstudio'))){
        $('paisEstudio').addEvent('change', function(event){

            var ajax = new Request({
                method: 'get',
                url: "/aplicantes/client.ngmf?op=tipoEstudios&idpais="+$('paisEstudio').value,
                onRequest: function(){
                    $('tipoDeEstudio').setAttribute('disabled', 'disabled');
                    $('tipoDeEstudio').getParent().addClass('cargando');
                },
                onFailure: function(){},
                onSuccess: function(texto, xmlrespuesta) {
                    $('tipoDeEstudio').innerHTML = texto;
                    $('tipoDeEstudio').getParent().removeClass('cargando');
                    $('tipoDeEstudio').removeAttribute('disabled');
                }
            }).send();

            var ajax2 = new Request({
                method: 'get',
                url: "/aplicantes/client.ngmf?op=instituciones&idpais="+$('paisEstudio').value,
                onRequest: function(){
                    $('ins_institucion').setAttribute('disabled', 'disabled');
                    $('ins_institucion').getParent().addClass('cargando');
                },
                onFailure: function(){},
                onSuccess: function(texto, xmlrespuesta) {
                    $('ins_institucion').innerHTML = texto;
                    $('ins_institucion').getParent().removeClass('cargando');
                    $('ins_institucion').removeAttribute('disabled');
                }
            }).send();

        });
    }


    if($chk($('promedio')) && $chk($('rango'))){
        $('rango').addEvent('blur', function(event){

            var ajax = new Request({
                method: 'get',
                url: "/aplicantes/client.ngmf?op=validarPromedio&promedio="+$('promedio').value+"&rango="+$('rango').value,
                onRequest: function(){},
                onFailure: function(){},
                onSuccess: function(texto, xmlrespuesta) {
                    if(texto == 'ok'){
                        $('promedio').getParent().removeClass('requerido');
                        $('promedio').getParent().getElement('label').removeClass('requerido');
                        var aux = $('promedio').title;
                        $('promedio').title = $('promedio').getAttribute('rel');
                        $('promedio').setAttribute('rel',aux);
                    }else{
                        var aux = $('promedio').title;
                        $('promedio').title = $('promedio').getAttribute('rel');
                        $('promedio').setAttribute('rel',aux);
                        $('promedio').getParent().addClass('requerido');
                        $('promedio').getParent().getElement('label').addClass('requerido');
                    }
                }
            }).send();
        });
    }
    
    
    if($chk($('filemanager-photoupload'))){
 	
 
        var swiffy = new FancyUpload2($('filemanager-status'), $('filemanager-list'), {
            url: '/aplicantes/client.ngmf',
            fieldName: 'photoupload',
            method: 'post',
            data: {
                'op':'uploadFiles',
                'idu':$('idu').value,
                'idc':$('idc').value
                },
            path: '/externos/fancyupload/Swiff.Uploader.swf',
            limitSize: 2 * 1024 * 1024, // 2Mb
            instantStart: false,
            queued: true,
            multiple: true,
            onLoad: function() {
                $('filemanager-status').removeClass('hide');
                $('filemanager-fallback').destroy();
            },
            onComplete: function() {
                window.location = '?';
            },
            // The changed parts!
            debug: false, // enable logs, uses console.log
            target: 'filemanager-browse' // the element for the overlay (Flash 10 only)
        });
 
        /**
	 * Various interactions
	 */
 
        $('filemanager-browse').addEvent('click', function() {
            /**
		 * Doesn't work anymore with Flash 10: swiffy.browse();
		 * FancyUpload moves the Flash movie as overlay over the link.
		 * (see opeion "target" above)
		 */
            swiffy.browse();
            return false;
        });

 
        $('filemanager-upload').addEvent('click', function() {
            swiffy.upload();
            return false;
        });

    }

    if($chk($('foto'))){
	
        var link = $('foto');
        var linkIdle = link.get('html');
		var div = null;
	
        function linkUpdate() {
            if (!swf.uploading) return;
            var size = Swiff.Uploader.formatUnit(swf.size, 'b');
            link.set('html', '<span><strong>' + swf.percentLoaded + '%</strong><br /> de ' + size + '</span>');
        }
	
        // Uploader instance
        var swf = new Swiff.Uploader({
            path: '/externos/fancyupload/Swiff.Uploader.swf',
            url: '/aplicantes/client.ngmf?op=uploadFoto',
            verbose: false,
            queued: false,
            multiple: false,
            target: link,
            instantStart: true,
            typeFilter: {
                'Images (*.jpg, *.jpeg, *.gif, *.png)': '*.jpg; *.jpeg; *.gif; *.png'
            },
            fileSizeMax: 2 * 1024 * 1024,
            onSelectSuccess: function(files) {
                //if (Browser.Platform.linux) window.alert('Warning: Due to a misbehaviour of Adobe Flash Player on Linux,\nthe browser will probably freeze during the upload process.\nSince you are prepared now, the upload will start right away ...');
                this.setEnabled(false);
            },
            onSelectFail: function(files) {
            },
            appendCookieData: true,
            onQueue: linkUpdate,
            onFileComplete: function(file) {
				var params = JSON.decode(file.response.text, false);
				div = new Element('div',{'styles':{'height':params.width+'px','width':params.height+'px'}});
				var img_foto = new Element('img', {'src': params.hash,'id': 'img_foto'});
                div.grab(img_foto);
                file.remove();
                this.setEnabled(true);
            },
            onComplete: function() {
				link.empty();
                link.grab(div);
            }
        });
	
        // Button state
        link.addEvents({
            click: function() {
                return false;
            },
            mouseenter: function() {
                this.addClass('hover');
                swf.reposition();
            },
            mouseleave: function() {
                this.removeClass('hover');
                this.blur();
            },
            mousedown: function() {
                this.focus();
            }
        });

    }
	
    if($chk($$("#form_cv.tecnico"))){
        $$("#form_cv.tecnico tr").each(function(el, count) {
            if (count % 2 == 0) {
                el.addClass('alt');
            }
        });
    }
	
    if($chk($('imprimir'))){
        var css_print_preview = null;
        $('imprimir').addEvent('click', function(event){
            event.stop();
            css_print_preview = new Asset.css('css/layouts/cv_print_preview.css');
        });
		
        $('volver').addEvent('click', function(event){
            event.stop();
            css_print_preview.dispose();
        });
    }

    $each($$('button[type=submit]'),function(el) {
        el.addEvent('dblclick',function(e) {
           this.disabled = 1;
        }.bind(el));
    });

});

    