var fill = "";
var url_files = "";
var clicks = 0;
var editable;

if ( typeof document != 'undefined' && document.readyState != 'complete' && window.addEventListener ) {
    window.addEventListener( 'DOMContentLoaded', function(e) {
        init();
        window.addEventListener( "scroll", posicionar, false );
        window.addEventListener( "resize", posicionar, false );
        window.addEventListener( "load", posicionar, false );
    });
}
else {
    $( window ).ready( function() {
        init();
    });
    $( window ).resize( function() {
        posicionar();
    });
    $( window ).load( function() {
        posicionar();
    });
    $( window ).scroll( function() {
        posicionar();
    });
}

function posicionar() {
    if( $( "#intro_text" ).html() == null ) {
        if ( ! $( '#visor' ).hasClass( "jspScrollable" ) ) {
            $( '#visor' ).jScrollPane({
                contentWidth: 0,
                horizontalGutter: -30,
                verticalGutter: -30
            });
        }
    }
    else {
        if ( ! $( '#visor' ).hasClass( "jspScrollable" ) ){
            $( '#visor' ).jScrollPane({
                contentWidth: 0,
                horizontalGutter: -30,
                verticalGutter: -30
            });
        }
    }
    ims.interfaz.resize();
}

function init() {

    config_xml = $.parseXML( config_xml );
    url_files = $( config_xml ).find( 'path' ).text();

    ims.interfaz.setSound( 'good', url_interfaz +'audio/good.mp3' );
    ims.interfaz.setSound( 'rBad', url_interfaz +'audio/result_bad.mp3' );
    ims.interfaz.setSound( 'rGood', url_interfaz +'audio/result_good.mp3' );
    ims.interfaz.setSound( 'beep_select', url_interfaz +'audio/beep_select.mp3');
    
    ims.interfaz.init();
    inmediastudio.TRAZA.init();

    $( "#visor" ).append( "<div id='visor_content'></div>" );
    $( "#url_interfaz" ).remove();
    $( "#overall" ).remove();
    
    retornar();
    
    if( typeof editable != "undefined" || $( config_xml ).find( "introduccion" ).find( "texto1" ).text().length === 0 ) {
        cargar_actividad();
    }
    else {
        inicializar();
    }
}

function inicializar() {
    
    ims.interfaz.setTitle( $( config_xml ).find( "introduccion" ).find( "titulo" ).text() );
    var IntTit = $( config_xml ).find( "palabras" ).find( "introduccion" ).text();
    var IntTex = $( config_xml ).find( "introduccion" ).find( "texto1" ).text();
    $( "#visor_content" ).append( '<div id="intro_title">'+ IntTit +'</div><div id="intro_text">'+ IntTex +'</div>' );

    var comenzar = $( config_xml ).find( "comenzar" ).text();
    ims.interfaz.addButton( "Siguiente", "right", "siguiente ", comenzar );
    ims.interfaz.enable( "Siguiente" );
    ims.interfaz.bind( "Siguiente", 'nextPage()' );
    posicionar();
}

function cargar_actividad() {
    
    if( $( config_xml ).find( "pregunta" ).find( "foto" ).length !== 0 ) {
        
        var foto_object = $( config_xml ).find( "pregunta" ).find( "foto" );
        var foto = foto_object.text();
        var rotation = foto_object.attr( "rotation" );
        var width = foto_object.attr( "width" );
        var height = foto_object.attr( "height" );
        var x = parseInt( foto_object.attr( "x" ) );
        var y = parseInt( foto_object.attr("y") );

        if ( !showHeader ) {
            y = y - HEADER_HEIGHT;
        }
        if ( foto != '' ) {
            if( /MSIE (\d+\.\d+);/.test( navigator.userAgent ) ) {
                var ieversion = new Number( RegExp.$1 );
                if ( ieversion >= 8 ) {
                    foto = url_files + foto;
                    $( "#fondo" ).append( '<div><img style="position:absolute;margin-left:'+ x +"px;margin-top:" + y +"px;width:"+ width +"px;height:"+ height +'px; src="'+ foto + '"/></div>');
                    if ( x == "" && y == "" ) {
                        height = parseInt( $( '#fondo div img' ).height() );
                        width = parseInt( $( '#fondo div img' ).width() );
                        if ( width < $( "#fondo" ).width() || height < $( "#fondo" ).height() ) {
                            x = $( "#fondo" ).offset().left + $( "#fondo" ).width() - width;
                            y = $( "#fondo" ).offset().top + $( "#fondo" ).height() - height;
                            y = parseInt( y );
                            $( '#fondo div img' ).css({
                                "margin-left": x +"px ",
                                "margin-top": y +"px"
                            });
                        }
                    }
                }
            }
            else {
                $( '#fondo' ).css( "background-repeat", "no-repeat" );
                if ( url_files != "" ) {
                    $( '#fondo' ).css( "background-image", "url("+ url_files + foto +")" );
                }
                else {
                    $( '#fondo' ).css( "background-image", "url("+url_files + foto +")" );
                }
                if ( rotation != '' ) {
                    $('#fondo').css( "rotation", rotation );
                }
                if ( x != '' || y != '' ) {
                    $('#fondo').css( "background-position", x +"px "+ y +"px" );
                    if ( width != '' && height != '' ) {
                        $('#fondo').css( "background-size", width +"px "+ height +"px" );
                    }
                    else {
                        if ( height != '' ) {
                            $( '#fondo' ).css( "background-size", "auto "+ height +"px" );
                        }
                        else {
                            if ( width != '' ) {
                                $( '#fondo' ).css( "background-size", width +"px auto" );
                            }
                        }
                    }
                }
            }
            url = $( '#fondo' ).css( 'background-image' ).replace( 'url(', '' ).replace( ')', '' ).replace( "'", '' ).replace( '"', '' );
            bgImg = $( '<img/>' );
            bgImg.hide();
            if( x == "" && y == "" ) {
                bgImg.bind( 'load', function() {
                    height = parseInt( $( this ).height() );
                    width = parseInt( $( this ).width() );
                    if ( width < $( "#fondo" ).width() || height < $( "#fondo" ).height() ) {
                        x = $( "#fondo" ).offset().left + $( "#fondo" ).width() - width;
                        y = $( "#fondo" ).offset().top + $( "#fondo" ).height() - height;
                        $( '#fondo' ).css( "background-position", x +"px "+ y +"px" );
                    }
                    bgImg.remove();
                });
            }
            $('#fondo').append( bgImg );
            bgImg.attr( 'src', url );
        }
    }

    var silenciar = $( config_xml ).find( "silenciar" ).text();
    var ayuda = $( config_xml ).find( "palabras" ).find( "ayuda" ).text();
    var comprobar = $( config_xml ).find( "comprobar" ).text();
    var clave = $( config_xml ).find( "desarrollo" ).text();
    var imprimir = $( config_xml ).find( "imprimir" ).text();
    var versolucion = $( config_xml ).find( "versolucion" ).text();
    var reiniciar = $( config_xml ).find( "reiniciar" ).text();
    var volver = $( config_xml ).find( "volver" ).text();
    
    if ( !isMobile ){
        ims.interfaz.addButton( "silenciar1", "left", "silenciar", silenciar );
    }
    if ( $( config_xml ).find("sonido").text() != '' ) {
        ims.interfaz.addButton( "pausar", "left", "pause", $( config_xml ).find( "pausa" ).text() );
        ims.interfaz.addButton( "player", "left", "play", $( config_xml ).find( "reproducir" ).text() );
    }
    if ( !isMobile && $( config_xml ).find( "urlimprimir" ).text().length > 0 ){
        ims.interfaz.addButton( "imprimir1", "left", "imprimir", imprimir );
    }
    ims.interfaz.addButton( "Anterior", "left", "anterior", volver );
    ims.interfaz.addButton( "ayuda0", "right", "ayuda", ayuda );
    ims.interfaz.addButton( "comprobar1", "right", "comprobar", comprobar );
    ims.interfaz.addButton( "versolucion2", "right", "versolucion", versolucion );
    ims.interfaz.addButton( "clave1", "right", "clave", clave );
    ims.interfaz.addButton( "reiniciar4", "right", "reiniciar", reiniciar );
    
    if ( $( config_xml ).find( "introduccion" ).find( "texto1" ).text().length !== 0 ) {
        ims.interfaz.enable( "Anterior" );
        ims.interfaz.bind( "Anterior", 'prevPage()' );
    }
    if ( !isMobile ){
        ims.interfaz.enable( "silenciar1" );
        if ( ims.interfaz.sound ) {
            ims.interfaz.bind( "silenciar1", "mute()" );
        }
        else {
            ims.interfaz.bind( "silenciar1", "play()" );
        }
    }

    if( $( config_xml ).find( "ayuda" ).find( "texto1" ).text().length !== 0 ) {
        ims.interfaz.addPopup( "ayuda", "ayuda0" );
        var ayudaTit = $( config_xml ).find( "ayuda" ).find( "titulo" ).text();
        var ayudaTex = $( config_xml ).find( "ayuda" ).find( "texto1" ).text();
        $( '.pop_up' ).prepend( "<span class='pop_up_title'>"+ ayudaTit + "</span>" );
        $( '#content_ayuda' ).append( '<div id="contenidoPOP">'+ ayudaTex +'</div>' );
        ims.interfaz.resize();
    }

    ims.interfaz.bind( "reiniciar4", 'reload()' );
    ims.interfaz.bind( "comprobar1", 'comprobar()' );
    ims.interfaz.bind( "imprimir1", "imprimir()" );
    ims.interfaz.enable( "reiniciar4" );
    ims.interfaz.enable( "comprobar1" );
    ims.interfaz.enable( "imprimir1" );
    
    crucigrama();

    $( "#limit" ).css( 'z-index','1000' );
    
    var _input = $( "<input/>" ).attr( "type", "text" ).attr( "id", "oculto" ).css({
        'z-index': "0",
        'position': 'absolute',
        'overflow': 'hidden',
        'outline': 'none',
        'clip': 'rect(0 0 0 0)',
        'height': '3px',
        'width': '3px',
        'margin': '-1px',
        'padding': '0',
        'border': '0',
        '-webkit-appearance':'none'
    });

    _input.bind({
        focusout: function() {
            if ( isAndroid ) {
                editable = undefined;
                $( ".amarillo" ).removeClass( 'amarillo' );
                $( ".foco" ).removeClass( 'foco' );
                $( "tr td div" ).each( function() {
                    if ( $( this ).text() == '|' ){
                        $( this ).text('');
                    }
                });
            }
        },
        keydown: function() {
        },
        keyup: function(e) {
            if ( $( "#oculto" ).val().length > 1 ) {
                letra = $( "#oculto" ).val()[ $( "#oculto" ).val().length-1 ];
            }
            else {
                letra = $( "#oculto" ).val();
            }
            if ( letra != '' && letra != '´' && letra != '`' && letra != '¨' ) { 
                if ( letra=='ä' || letra=='ë' || letra=='ï' || letra=='ö' || letra=='ü' || letra=='á' || letra=='é' || letra=='í' || letra=='ó' || letra=='ú' || letra=='à'
                    || letra=='è'|| letra=='ì'|| letra=='ò'|| letra=='ù') {
                    var _orient = $( this ).attr( 'orient' );
                    var _id = $( this ).attr( "idw" );
                    var _x = 0;
                    var _y = 0;
                    var _inc = 50;
                    switch ( _orient ) {
                        case 'v':
                            var coord = _id.split( '_' );
                            _y = coord[0];
                            _x = coord[1];
                            _inc = 50;
                            if ( $( "#"+ _y+ "_"+ _x ).length > 0 && !$( "#"+ _y +"_"+ _x ).hasClass( 'isCell' ) ) {
                                $( "#"+ _y +"_"+ _x ).html( letra );
                            }
                            _y++;
                            break;
                        case 'h':
                            var coord = _id.split( '_' );
                            _y = coord[0];
                            _x = coord[1];
                            if ( $ ( "#"+ _y +"_"+ _x).length > 0 && !$( "#"+ _y +"_"+ _x).hasClass( 'isCell' ) ) {
                                $( "#"+ _y +"_"+ _x ).text( letra );
                            }
                            _x++;
                            break;
                        case 'vi':
                            var coord = _id.split( '_' );
                            _y = coord[0];
                            _x = coord[1];
                            _inc = 550;
                            if ( $ ( "#"+ _y +"_"+ _x ).length > 0 && !$( "#"+ _y +"_"+ _x).hasClass( 'isCell' ) ) {
                                $( "#"+ _y +"_"+ _x ).text( letra );
                            }
                            _y--;
                            break;
                        case 'hi':
                            var coord = _id.split( '_' );
                            _y = coord[0];
                            _x = coord[1];
                            if ( $ ( "#"+ _y +"_"+ _x ).length > 0 && !$( "#"+ _y +"_"+ _x ).hasClass( 'isCell' ) ) {
                                $( "#"+ _y +"_"+ _x ).text( letra );
                            }
                            _x--;
                            break;
                    }
                    if( isAndroid ){
                        editable = '';
                    }
                    $( ".amarillo" ).removeClass( 'amarillo' );
                    $( ".foco" ).removeClass( 'foco' );
                    if( !$( "#"+ _y +"_"+ _x ).hasClass( 'isCell' ) ) {
                        $( "#"+ _y +"_"+ _x).text( "|" ).addClass( "foco" );
                    }
                    $( this ).attr( "idw", _y +"_"+ _x );
                    if( isMobile ) {
                        var _w = document.width/window.innerWidth;
                        var topOriginalZoom = $( ".foco" ).offset().top - ( ( $( ".foco" ).offset().top ) *_w );
                        var topO = -( $( ".foco" ).offset().top - $( "#header" ).outerHeight() );
                        var leftOriginalZoom = $( ".foco" ).offset().left - ( ( $( ".foco" ).offset().left - $( "#limit" ).offset().left + 150 )*_w );
                        var leftO = ( ( $( ".foco" ).offset().left - $( "#limit" ).offset().left - ( $( ".foco" ).offset().left - $( "#limit" ).offset().left ) * _w ) / _w );
                        _inc = ( $( ".foco" ).offset().top - ( $( ".foco" ).offset().top * _w ) ) /_w;
                    }
                    if( !$( "#"+ _y +"_"+ _x ).attr( 'class' ) ) {
                        _input.blur();
                    }
                    $( "#oculto" ).val( null );
                    }
                else {
                    
                    e.preventDefault();
                    
                    var code = e.keyCode || e.which,
                        _char = '';
                    
//                    if ( code == 192 ) {
//                        _char = 'Ñ';
//                    }
//                    else {
                        _char = letra;
//                    }
                    
                    var _orient = $( this ).attr( 'orient' );
                    var _id = $( this ).attr( "idw" );
                    var _x = 0;
                    var _y = 0;
                    var _inc = 50;
                    var coord;
                    
                    switch ( _orient ) {
                        case 'v':
                            coord = _id.split( '_' );
                            _y = coord[0];
                            _x = coord[1];
                            _inc = 50;
                            if ( $( "#"+ _y +"_"+ _x ).length > 0 && !$( "#"+ _y +"_"+ _x ).hasClass( 'isCell' ) ) {
                                $( "#"+ _y +"_"+ _x ).text( _char );
                            }
                            _y++;
                            break;
                        case 'h':
                            coord = _id.split( '_' );
                            _y = coord[0];
                            _x = coord[1];
                            if ( $ ( "#"+ _y +"_"+ _x ).length > 0 && !$( "#"+ _y +"_"+ _x ).hasClass( 'isCell' ) ) {
                                $( "#"+ _y +"_"+ _x ).text( _char );
                            }
                            _x++;
                            break;
                        case 'vi':
                            coord = _id.split( '_' );
                            _y = coord[0];
                            _x = coord[1];
                            _inc = 550;
                            if ( $( "#"+ _y +"_"+ _x ).length > 0 && !$( "#"+ _y +"_"+ _x ).hasClass( 'isCell' ) ) {
                                $( "#"+ _y +"_"+ _x ).text( _char );
                            }
                            _y--;
                            break;
                        case 'hi':
                            coord = _id.split( '_' );
                            _y = coord[0];
                            _x = coord[1];
                            if ( $( "#"+ _y +"_"+ _x).length > 0 && !$( "#"+ _y +"_"+ _x ).hasClass( 'isCell' ) ) {
                                $( "#"+ _y +"_" +_x ).text( _char );
                            }
                            _x--;
                            break;
                    }

	                var _w = document.width / window.innerWidth;
	                if ( isAndroid ){
	                    editable = '';
	                }
	                if ( !$( "#"+ _y +"_"+ _x ).attr( 'class' ) ){
	   					_input.blur();
	                }
	                $( ".amarillo" ).removeClass( 'amarillo' );
	                $( ".foco" ).removeClass( 'foco' );
	                if ( !$( "#"+ _y +"_"+ _x ).hasClass( 'isCell' ) ) {
	                    $( "#"+ _y +"_"+ _x).text( "|" ).addClass( "foco" );
	                }
	                $(this).attr( "idw", _y +"_"+ _x );
	            }
                letra = '';
                $( "#oculto" ).val('');
            }
        }
    });
    $( "#visor" ).append( _input );
    setClass();

    $( "tr td div" ).bind( 'click', function(e) {
        $( "tr td div" ).each( function() {
            if( $( this ).text() == '|' ){
                $( this ).text( '' );
            }
        });
        e.preventDefault();
        $( "#oculto" ).select();
        var _id = $( this ).attr( 'id' );
        $( ".amarillo" ).removeClass( 'amarillo' );
        var clase = $( this ).attr( "class" );
        var _maxLength = 0;
        
        if ( clase.indexOf( " " ) != "-1" ) {
            var data = nearOrientation( $( this ), clicks ).split( " " ),
                orient = data[0],
                clase = data[1];
                if ( clase == '' ) {
                    clase = data[2];
                }
                $( "."+ clase ).each( function() {
                    
                    if( !$( this ).hasClass( "isCell" ) ) {
                        $( this ).addClass( "amarillo" );
                    }
                });
        }
        else {
            orient = getOrientation( $( this ), clase );
            $( "."+ clase ).each( function() {
                if ( ! $( this ).hasClass( "isCell" ) ) {
                    $( this ).addClass( "amarillo" );
                }
            });
        }
        var _x;
        var _y;
        
        coord = _id.split( '_' );
        _y = coord[0];
        _x = coord[1];
        
        switch ( orient ) {
            case 'v':
                $( "." +clase ).each( function() {
                    if( $( "#"+ _y +"_"+ _x ).length > 0 ) {
                        _maxLength++;
                    }
                    _y++;
                });
                break;
            case 'h':
                $( "."+ clase ).each( function() {
                    if( $( "#"+ _y +"_"+ _x ).length > 0 ) {
                        _maxLength++;
                    }
                    _x++;
                });
                break;
            case 'vi':
                $( "."+ clase ).each( function() {
                    if( $( "#"+ _y +"_"+ _x ).length > 0 ) {
                        _maxLength++;
                    }
                    _y--;
                });
                break;
            case 'hi':
                $( "." + clase ).each( function() {
                    if ( $( "#"+ _y +"_"+ _x ).length > 0 ) {
                        _maxLength++;
                    }
                    _x--;
                });
                break;
        }
        
        $( this ).text( "|" );
        
        $( "#oculto" ).attr({
            'maxlength': _maxLength,
            'orient': orient,
            'idw': _id
        }).css({
            'left': $(this).position().left + 'px',
            'top': $(this).position().top + 'px'
        });

        if ( isAndroid ) {
            editable = '';
        }

        $( ".amarillo" ).removeClass( 'amarillo' );
        $( ".foco" ).removeClass( 'foco' );

        $( this ).text( "|" ).addClass( "foco" );
    });

    var tA = 0;

    $( "#ayuda0" ).click( function() {
        if ( tA === 0 ) {
            $( "#content_ayuda" ).width( $( "#content_ayuda" ).width() );
            $( '#content_ayuda' ).jScrollPane({
                showArrows: false,
                hideFocus: true
            });
            tA++;
        }
    });

    posicionar();
}

function crucigrama() {
    
    $( config_xml ).find( "pregunta" ).each( function() {

        var crucigrama = "";
        var j = 0;
        
        ims.interfaz.setTitle( $( config_xml ).find( "introduccion" ).find( "titulo" ).text() );
        
        var enunciado = $( this ).find( "enunciado" ).text().replace( /<p>/g, "" ).replace( /<\/p>/g, "" );
        $( '#pregunta' ).append( enunciado );
        
        var pistas = $( this ).find( "pistas" ).text();
        $( this ).find( "pistas" ).find( "pista" ).each( function() {
            fill += '<div class="number"><p>'+ (parseInt( $( this ).attr( "id" ) ) + 1) +'</p></div><div class="pista">'+ $( this ).text().replace( "<p>", "" ).replace( "</p>", "" ) +'</div><div style="clear:both;"></div>';
        });
        $( "#visor_content" ).append( '<div id="IZQ">'+ fill +"</div>" );
        fill = "";

        crucigrama += '<div id="tabla"><table border="0" cellpadding="0" id="crucigrama" cellspacing="0">';
        
        $( this ).find( "matriz" ).find( "fila" ).each( function() {
            
            var celdas = $( this ).text().split( "," );
            var i = 0;
            crucigrama += '<tr id="'+ (j++) +'">';
            while( i <= ( celdas.length - 1 ) ) {
                if ( celdas[i] === "#" ) {
                    crucigrama += '<td class="noClass" id="'+ i +'""></td>';
                }
                else {
                    if ( celdas[i].indexOf( '¿' ) != -1 ) {
                        crucigrama += '<td id="'+ (j - 1) +"_"+ i +'" class="isCell" alt="isCell">'+ celdas[i].replace( /¿/g, "" ) +"</td>";
                    }
                    else {
                        crucigrama += '<td id="'+ i +'"><div spellcheck="false" id="'+ (j - 1) +"_"+ i +'"></div></td>';
                    }
                }
                i++;
            }
            crucigrama += "</tr>";
        });
        crucigrama += "</table></div>";
        fill += crucigrama;

        $( "#visor_content" ).append( '<div id="DER">'+ fill +"</div>");
    });

    $( "table tr" ).each( function() {
        
        var _this = $( this );
        var _n_child = 0;
        var _child = _this.children();
        
        _this.attr( "hC", "false" );
        
        _child.each( function (){
            if ( $( this ).children().length > 0 || $( this ).hasClass( "isCell" ) ) {
                _n_child++;
            }
        });
        if ( _n_child !== 0 ) { 
            _this.attr( "hC", "true" );
        }
        if ( _n_child === 0 && _this.prev().attr( "hC" ) != 'true' ) {
            _this.hide();
        }
    });
}

function Keypress() {
    
    $( "input" ).keypress( function() {

        var arr = $( this ).attr( "id" ).split( "_" );
        var next = parseInt( arr[1] ) + 1;
        
        setTimeout( function() {
            if ( orient == "h" ) {
                if ( $( "#"+ arr[0] +"_"+ ( next + 1 ) ).val() == "" || $( "#"+ arr[0] +"_"+ ( next ) ).val() == "" ) {
                    $( "#"+ arr[0] +"_"+ next ).select();
                }
                else {
                    $( "#"+ arr[0] +"_"+ next ).select();
                    $( "#"+ arr[0] +"_"+ next ).val( "" );
                }
            }
            if ( orient == "hi" ) {
                if ( $( "#"+ arr[0] +"_"+ ( next - 2 ) ).val() == "" || $( "#"+ arr[0] +"_"+ ( next - 3 ) ).val() == "" ) {
                    $( "#"+ arr[0] +"_"+ ( next - 2 ) ).select();
                }
                else {
                    $( "#"+ arr[0] +"_"+ ( next - 2 ) ).select();
                    $( "#"+ arr[0] +"_"+ ( next - 2 ) ).val( "" );
                }
            }
            if ( orient == "v") {
                if ( $( "#"+ ( parseInt( arr[0] ) + 1 ) +"_"+ ( next - 1 ) ).val() == "" || $( "#"+ ( parseInt( arr[0] ) + 2 ) +"_"+ ( next - 1 ) ).val() == "" ) {
                    $( "#"+ ( parseInt( arr[0] ) + 1 ) +"_"+ ( next - 1 ) ).select();
                }
                else {
                    $( "#"+ ( parseInt( arr[0] ) + 1 ) +"_"+ ( next - 1 ) ).select();
                    $( "#"+ ( parseInt( arr[0] ) + 1 ) +"_"+ ( next - 1 ) ).val( "" );
                }
            }
            if ( orient == "vi" ) {
                if( $( "#"+ ( parseInt( arr[0] ) - 1 ) +"_"+ ( next - 1 ) ).val() == "" || $( "#"+ ( parseInt( arr[0] ) - 2 ) +"_"+ ( next - 1 ) ).val() == "" ) {
                    $( "#"+ ( parseInt( arr[0] ) - 1 ) +"_"+ ( next - 1 ) ).select();
                }
                else {
                    $( "#"+ ( parseInt( arr[0] ) - 1 ) +"_"+ ( next - 1 ) ).select();
                    $( "#"+ ( parseInt( arr[0] ) - 1 ) +"_"+ ( next - 1 ) ).val("");
                }
            }
        }, 50);
    });
}

function checkInput() {
    $( "input" ).toggle( function() {
        var clase = $( this ).attr( "class" );
        $( ".amarillo" ).removeClass( "amarillo" );
        if ( clase.indexOf( " " ) != "-1" ) {
            var data = nearOrientation( $( this ) ).split( " " );
            orient = data[0];
            clase = data[1];
            
            $( "."+ clase ).each( function() {
                if ( !( $( this ).hasClass( "isCell" ) ) ) {
                    $( this ).addClass( "amarillo" );
                }
            });
            return;
        }
        orient = getOrientation( $( this ), clase );
        $( "."+ clase ).each( function() {
            if ( !( $( this ).hasClass( "isCell" ) ) ) {
                $( this ).addClass( "amarillo" );
            }
        });
    }, function() {
        var clase = $( this ).attr( "class" );
        $( ".amarillo" ).removeClass( "amarillo" );
        clase = clase.split( " " );
        orient = getOrientation( $( this ), clase[0] );
        $( "."+ clase[0] ).each( function() {
            if ( !( $( this ).hasClass( "isCell" ) ) ) {
                $( this ).addClass( "amarillo" );
            }
        });
    });
}

function setClass() {
    
    $( config_xml ).find( "palabra" ).each( function(c) {
        var iniy = parseInt( $( this ).attr( "iniy" ) );
        var inix = parseInt( $( this ).attr( "inix" ) );
        var finy = $( this ).attr( "finy" );
        var finx = $( this ).attr( "finx" );
        var o = $( this ).attr( "o" );
        if ( o == "right" ) {
            inix--;
            while ( inix <= finx ) {
                $( "#"+ iniy +"_"+ inix ).addClass( "selection_"+ c );
                inix++;
            }
        }
        if( o == "left" ) {
            inix++;
            while ( inix >= finx ) {
                $( "#"+ iniy +"_"+ inix ).addClass( "selection_"+ c );
                inix--;
            }
        }
        if( o == "up" ) {
            iniy++;
            while ( iniy >= finy ) {
                $( "#"+ iniy +"_"+ inix ).addClass( "selection_"+ c );
                iniy--;
            }
        }
        if( o == "down" ) {
            iniy--;
            while ( iniy <= finy ) {
                $( "#"+ iniy +"_"+ inix ).addClass( "selection_"+ c );
                iniy++;
            }
        }
    });
}

function nearOrientation( inputs, _clicks ) {
    
    var id = inputs.attr( "id" ).split( "_" );
    var i = 0;
    var clase = "";
    var x = id[1];
    var y = id[0];
    
    if ( _clicks === 0 ) {
        clicks = 1;
        if ( ( $( "#"+ y +"_"+ ( parseInt( x ) - 1 ) ).hasClass( "isCell" ) ) ) {
            clase = $( "#"+ y +"_"+ ( parseInt( x ) - 1 ) ).attr( "class" ).replace( "isCell", "" );
            return "h "+ clase;
        }
        if( ( $( "#"+ y +"_"+ ( parseInt( x ) + 1 ) ).hasClass( "isCell" ) ) ) {
            clase = $( "#"+ y +"_"+ ( parseInt( x ) + 1 ) ).attr( "class" ).replace( "isCell", "" );
            return "hi "+ clase;
        }
    }
    else {
        clicks = 0;
        if ( ( $( "#"+ ( parseInt( y ) - 1 ) +"_"+ x ).hasClass( "isCell" ) ) ) {
            clase = $( "#"+ ( parseInt( y ) - 1 ) +"_"+ x).attr( "class" ).replace( "isCell", "" );
            return "v "+ clase;
        }
        if ( ( $( "#"+ ( parseInt( y ) + 1 ) +"_"+ x ).hasClass( "isCell" ) ) ) {
            clase = $( "#"+ ( parseInt( y ) + 1 ) +"_"+ x ).attr( "class" ).replace( "isCell", "" );
            return "vi "+ clase;
        }
    }
    if ( ( $( "#"+ ( parseInt( y ) + 2 ) +"_"+ x ).hasClass( "isCell" ) ) ) {
        clase = $( "#"+ ( parseInt( y ) + 1 ) +"_"+ x ).attr( "class").replace( "isCell", "" );
        return "vi "+ clase;
    }
    if ( ( $( "#"+ y +"_"+ ( parseInt( x ) + 2 ) ).hasClass( "isCell" ) ) ) {
        clase = $( "#"+ y +"_"+ ( parseInt( x ) + 1 ) ).attr( "class" ).replace( "isCell", "" );
        return "hi "+ clase;
    }
    else {
        clase = $( "#"+ ( parseInt( y ) ) +"_"+ x ).attr( "class" ).split( ' ' )[0];
        if ( $( "."+ clase ).eq(0).hasClass( "isCell" ) ){
            return "h "+ clase;
        }
        else {
            return "hi "+ clase;
        }
    }
}

function getOrientation( inputs, clase ) {

    inputs.val( "" );
    var id = inputs.attr( "id" ).split( "_" );
    var direccion = "";
    var x = id[1];
    var y = id[0];
    var i = 0;
    
    if ( $( "#"+ y +"_"+ ( parseInt( x ) - 1 ) ).hasClass( "isCell" ) && $( "#"+ y +"_"+ ( parseInt( x ) - 1 ) ).hasClass( clase ) ) {
        return "h";
    }
    if( $( "#"+ y +"_"+ ( parseInt( x ) + 1 ) ).hasClass( "isCell" ) && $( "#"+ y +"_"+ ( parseInt( x ) + 1 ) ).hasClass( clase ) ) {
        return "hi";
    }
    if ( $( "#"+ ( parseInt( y ) - 1 ) +"_"+ x ).hasClass( "isCell" ) && $( "#"+ ( parseInt( y ) - 1 ) +"_"+ x ).hasClass( clase ) ) {
        return "v";
    }
    if ( $( "#"+ ( parseInt( y ) + 1 ) +"_"+ x ).hasClass( "isCell" ) && $( "#"+ ( parseInt( y ) + 1 ) +"_"+ x ).hasClass( clase ) ) {
        return "vi";
    }
    while ( i <= 14 ) {
        if ( $( "#"+ ( parseInt(y) - i) + "_" + x ).html() == null || typeof  $( "#"+ ( parseInt( y ) - i ) +"_"+ x ).html() == "undefined"  ){
            i = 15;
        }
        if ( $( "#"+ (y - i) +"_"+ x ).hasClass( "isCell" ) && $( "#"+ (y - i) +"_"+ x ).hasClass( clase ) ) {
            return "v";
        }
        i++;
    }
    i = 0;
    while ( i <= 14 ) {
        if ( $( "#"+ ( parseInt( y ) + i ) +"_"+ x ).html() == null || typeof $( "#"+ ( parseInt( y ) + i ) +"_"+ x ).html() == "undefined" ) {
            i = 15;
        }
        if ( $( "#"+ ( parseInt( y ) + i ) +"_"+ x ).hasClass( "isCell" ) && $( "#"+ ( parseInt( y ) + i) +"_"+ x ).hasClass( clase ) ) {
            return "vi";
        }
        i++;
    }
    i = 0;
    while ( i <= 14 ) {
        if ( $( "#"+ y +"_"+ (x - i) ).html() == null || typeof $( "#"+ y +"_"+ (x - i) ).html() == "undefined" ) {
            i = 15;
        }
        if ( $( "#"+ y +"_"+ (x - i) ).hasClass("isCell") && $( "#"+ y +"_"+ (x - i) ).hasClass( clase ) ) {
            return "h";
        }
        i++;
    }
    i = 0;
    while ( i <= 14 ) {
        if ( $( "#"+ y +"_"+ ( parseInt( x ) + i ) ).html() == null || typeof $( "#"+ y +"_"+ ( parseInt(x) + i ) ).html() == "undefined" ) {
            i = 15;
        }
        if ( $( "#"+ y +"_"+ ( parseInt( x ) + i ) ).hasClass( "isCell") && $( "#"+ y +"_"+ ( parseInt(x) + i ) ).hasClass( clase ) ) {
            return "hi";
        }
        i++;
    }
    clase = $( "#"+ ( parseInt( y ) ) +"_"+ x ).attr( "class" ).split( ' ' )[0];
    if ( $( "."+ clase ).eq(0).hasClass( "isCell" ) ){
        return "h"+ clase;
    }
    else {
        return "hi"+ clase;
    }
}

function comprobar() {
    if ( $( "#comprobar1" ).hasClass( "notdisabled" ) ) {
        var total = $( ".isCell" ).length;
        var correct = 0;
        $( "#comprobar1" ).removeClass( "notdisabled" );
        $( ".amarillo" ).removeClass( "amarillo" );
        if ( inmediastudio.TRAZA.mostrarSolucion ) { 
            $( "#versolucion2" ).addClass( "notdisabled" );
            ims.interfaz.bind( "versolucion2", "solucion()" );
        }
        else {
            $( "#reiniciar4" ).unbind( 'click' );
            $( "#reiniciar4" ).removeClass( "notdisabled" );
            $( "#Anterior" ).unbind( 'click' );
            $( "#Anterior" ).removeClass( "notdisabled" );
            $( "#comprobar1").unbind( 'click' );
        }
        
        $( "input[type=text]" ).attr( "readonly", "readonly" );
        if ( $( config_xml ).find( "solucion" ).find( "texto1").text().length !== 0 ) {
            if ( inmediastudio.TRAZA.mostrarSolucion ) { 
                ims.interfaz.enable( "clave1" );
                ims.interfaz.addPopup( "solucion", "clave1" );
            }
            $( config_xml ).find( "ES > solucion" ).each( function() {
                var solucionTit = $( this ).find( "titulo" ).text();
                var solucionTex = $( this ).find( "texto1" ).text();
                $( '#pop_solucion' ).prepend( "<span class='pop_up_title'>"+ solucionTit +"</span>" );
                $( '#content_solucion' ).append( '<div id="contenidoPOP">'+ solucionTex +'</div>' );
            });
            var tS = 0;
            $( "#clave1" ).click( function() {
                if( tS === 0 ){
                    $( "#content_solucion" ).width( $( "#content_solucion" ).width() );
                    $( '#content_solucion' ).jScrollPane({
                        showArrows: false,
                        hideFocus: true
                    });
                    tS++;
                }
                ims.interfaz.resize();
            });
        }
        
        $( config_xml ).find( "palabra" ).each( function() {
            var leng = $( this ).attr( "len" );
            var orient = $( this ).attr( "o" );
            var inix = $( this ).attr( "inix" );
            var iniy = $( this ).attr( "iniy" );
            var finx = $( this ).attr( "finx" );
            var finy = $( this ).attr( "finy" );
            var wordOk = $( this ).text();
            wordOk = wordOk.toUpperCase();
            var word = "";
            var idIni = iniy +"_"+ inix;
            var idFin = finy +"_"+ finx;
            var inicial = $( "#"+ iniy +"_"+ inix ).offset();
            var end = $( "#"+ finy +"_"+ finx).offset();
            
            if ( orient == "down" || orient == "up" ) {
                for( i = 0; i <= leng; i++ ) {
                    if( orient == "up" ) {
                        word += $( "#"+ parseInt( iniy-- ) +"_"+ inix ).text();
                    }
                    else {
                        word += $( "#"+ parseInt( iniy++ ) +"_"+ inix ).text();
                    }
                }
                if( word.toUpperCase() === wordOk ) {
                    correct++;
                    var iniy = $( this ).attr( "iniy" );
                    if ( inmediastudio.TRAZA.mostrarSolucion ) { 
                        for ( var i = 0; i <= leng; i++ ) {
                            if ( orient == "up" ) {
                                $( "#"+ parseInt( finy++ ) +"_"+ inix ).addClass( "green" ).width(23).css({
                                    "border-radius": "5px",
                                    "-webkit-border-radius": "5px",
                                    "-ms-border-radius": "5px",
                                    "-moz-border-radius": "5px"
                                });
                            }
                            else {
                                $( "#"+ parseInt( iniy++ ) +"_"+ inix ).addClass( "green" ).width(23).css({
                                    "border-radius": "5px",
                                    "-webkit-border-radius": "5px",
                                    "-ms-border-radius": "5px",
                                    "-moz-border-radius": "5px"
                                });
                            }
                        }
                        ims.interfaz.showStars( $( "#"+ parseInt( finy++ ) +"_"+ inix ) );
                    }
                }
                else {
                    var iniy = $( this ).attr( "iniy" );
                    if ( inmediastudio.TRAZA.mostrarSolucion ) { 
                        for( var i = 0; i <= leng; i++ ) {
                            if( orient == "up" ) {
                                $( "#"+ parseInt( finy++ ) +"_"+ inix ).addClass( "red" ).width(23).css({
                                    "border-radius": "5px",
                                    "-webkit-border-radius": "5px",
                                    "-ms-border-radius": "5px",
                                    "-moz-border-radius": "5px"
                                });
                            }
                            else {
                                $( "#"+ parseInt( iniy++ ) +"_"+ inix ).addClass( "red" ).width(23).css({
                                    "border-radius": "5px",
                                    "-webkit-border-radius": "5px",
                                    "-ms-border-radius": "5px",
                                    "-moz-border-radius": "5px"
                                });
                            }
                        }
                    }
                }
            }
            if ( orient == "right" || orient == "left" ) {
                for ( i = 0; i <= leng; i++ ) {
                    if ( orient == "left" ) {
                        word += $( "#"+ iniy +"_"+ inix-- ).text();
                    }
                    else {
                        word += $( "#"+ iniy +"_"+ inix++ ).text();
                    }
                }
                if( word.toUpperCase() === wordOk ) {
                    correct++;
                    var inix = $(this).attr( "inix" );
                    if ( inmediastudio.TRAZA.mostrarSolucion ) { 
                        for ( var i = 0; i <= leng; i++ ) {
                            if ( orient == "left" ) {
                                $( "#"+ iniy +"_"+ finx++ ).addClass( "green" ).width(23).css({
                                    "border-radius": "5px",
                                    "-webkit-border-radius": "5px",
                                    "-ms-border-radius": "5px",
                                    "-moz-border-radius": "5px"
                                });
                            }
                            else {
                                $( "#"+ iniy +"_"+ inix++ ).addClass("green").width(23).css({
                                    "border-radius": "5px",
                                    "-webkit-border-radius": "5px",
                                    "-ms-border-radius": "5px",
                                    "-moz-border-radius": "5px"
                                });
                            }
                        }
                        ims.interfaz.showStars( $("#"+ iniy +"_"+ finx++ ) );
                    }
                }
                else {
                    var inix = $( this ).attr( "inix" );
                    if ( inmediastudio.TRAZA.mostrarSolucion ) { 
                        for ( var i = 0; i <= leng; i++ ) {
                            if ( orient == "left" ) {
                                $( "#"+ iniy +"_"+ finx++ ).addClass("red").width(23).css({
                                    "border-radius": "5px",
                                    "-webkit-border-radius":"5px",
                                    "-ms-border-radius": "5px",
                                    "-moz-border-radius": "5px"
                                });
                            }
                            else {
                                $( "#"+ iniy +"_"+ inix++ ).addClass("red").width(23).css({
                                    "border-radius": "5px",
                                    "-webkit-border-radius": "5px",
                                    "-ms-border-radius": "5px",
                                    "-moz-border-radius": "5px"
                                });
                            }
                        }
                    }
                }
            }
        });
        
        if ( correct === total ) {
            var sound = "rGood";
        }
        else {
            var sound = "rBad";
        }
        ims.interfaz.showResults( "<p>"+ correct +" / "+ $( config_xml ).find( "palabra" ).length +"</p>" );
        if ( inmediastudio.TRAZA.mostrarSolucion ) { 
            ims.interfaz.playSound( sound );
        }
        if ( inmediastudio.TRAZA.guardarRespuesta ) {   
            inmediastudio.RESULTADOS.guardarPuntuacion( correct/total );
        }  
        return false;
    }
}

function solucion() {

    if( $( "#versolucion2" ).hasClass( "notdisabled" ) ) {
        
        sound = "good";
        ims.interfaz.playSound( sound );
        
        $( "input[type=text]" ).attr( "readonly", "readonly" );
        $( ".stars" ).remove();
        $( "#center" ).hide();
        $( "input" ).empty();

        ims.interfaz.disable( "versolucion2" );

        $( config_xml ).find( "palabra" ).each( function() {
            
            var leng = $( this ).attr( "len" );
            var orient = $( this ).attr( "o" );
            var inix = $( this ).attr( "inix" );
            var iniy = $( this ).attr( "iniy" );
            var finx = $( this ).attr( "finx" );
            var finy = $( this ).attr( "finy" );
            var wordOk = $( this ).text();
            var lengIn = $( this ).attr( "len" );
            var inicial = $( "#"+ iniy +"_"+ inix ).offset();
            var end = $( "#"+ finy +"_"+ finx).offset();
            
            if ( orient == "down" || orient == "up" ) {
                for ( var i = 0; i <= leng; i++ ) {
                    if ( orient == "up") {
                        ims.interfaz.showStars( $( "#"+ parseInt( finy ) +"_"+ inix ) );
                        $( "#"+ parseInt( finy++ ) +"_"+ inix ).text( wordOk[ lengIn-- ] ).addClass("green").attr('disabled', 'disabled').off('click');
                    }
                    else {
                        ims.interfaz.showStars( $( "#"+ parseInt( iniy ) +"_"+ inix) );
                        $( "#"+ parseInt( iniy++ ) +"_"+ inix ).text( wordOk[i] ).addClass("green").attr('disabled', 'disabled').off('click');
                    }
                }
            }
            if ( orient == "right" || orient == "left") {
                for ( var i = 0; i <= leng; i++ ){
                    if ( orient == "left" ) {
                        ims.interfaz.showStars( $( "#"+ iniy +"_"+ finx ) );
                        $( "#"+ iniy +"_"+ finx++ ).text( wordOk[lengIn--] ).addClass("green").attr('disabled', 'disabled').off('click');
                    }
                    else {
                        ims.interfaz.showStars( $( "#"+ iniy +"_"+ inix ) );
                        $( "#"+ iniy +"_"+ inix++ ).text( wordOk[i] ).addClass("green").attr('disabled', 'disabled').off('click');
                    }
                }
            }
        });
        
        return false;
    }
}

function imprimir() {
    
    window.open( $( config_xml ).find( "urlimprimir" ).text(), "Santillana", 'width=800,height=600' );
}

function prevPage() {
    fill = "";
    $( ".stars" ).remove();
    $( ".tooltip" ).remove( "" );
    $( "#limit" ).remove( "" );
    ims.interfaz.init();
    var element = $( "#visor" ).jScrollPane().data().jsp;
    element.destroy();
    $( "#visor" ).append( "<div id='visor_content'></div>" );
    $( "#overall" ).remove();
    inicializar();
    retornar();
}

function nextPage() {
    $( ".tooltip" ).remove( "" );
    $( "#limit" ).remove( "" );
    ims.interfaz.init();
    var element = $( "#visor" ).jScrollPane().data().jsp;
    element.destroy();
    $( "#visor" ).append( $( "<div/>" ).attr( "id", "visor_content" ) );
    $( "#overall" ).remove();
    play();
    cargar_actividad();
    retornar();
}

function retornar() {
	introduce_retorno();
}

function reload() {
    $( "#oculto" ).die( 'keypress' );
    fill = "";
    $( ".stars" ).remove();
    $( ".tooltip" ).remove();
    $( "#limit" ).remove();
    ims.interfaz.init();
    var element = $( "#visor" ).jScrollPane().data().jsp;
    element.destroy();
    $( "#visor" ).append( $( "<div/>" ).attr( "id", "visor_content" ) );
    $( "#overall" ).remove();
    cargar_actividad();
    if ( !ims.interfaz.sound ) {
        mute();
    }
    retornar();
}

function mute() {
    $( '.tooltip' ).hide();
    $( '#silenciar1' ).attr( 'title', $( config_xml ).find( "silenciar" ).text() );
    $( '#silenciar1' ).removeClass( 'silenciar' );
    $( '#silenciar1' ).addClass( 'silenciar_on' );
    $( '#silenciar1' ).tooltip();
    ims.interfaz.bind( "silenciar1", "play()" );
    ims.interfaz.disableSound();
}

function play() {
    $( '.tooltip' ).hide();
    $( '#silenciar1' ).attr( 'title', $(config_xml).find( "silenciar" ).text() );
    $( '#silenciar1' ).removeClass( 'silenciar_on' );
    $( '#silenciar1' ).addClass( 'silenciar' );
    $( '#silenciar1' ).tooltip();
    ims.interfaz.bind( "silenciar1", "mute()" );
    ims.interfaz.enableSound();
}