var passok = false;
var repassok = false;
var nombreok = false;
var emailok = false;

function ajaxInit() {// Initialize the AJAX variable.  
    var ajax = null;
    if (window.XMLHttpRequest) {                     // Does this browser have an XMLHttpRequest object?
        ajax=new XMLHttpRequest();                    // Yes -- initialize it.
    } else {                                         // No, try to initialize it IE style
        //  Wheee, ActiveX, how do we format c: again?
        ajax=new ActiveXObject("Msxml2.XMLHTTP");     //Version newer IE 5
        if (ajax==null){
            ajax=new ActiveXObject("Microsoft.XMLHTTP");//Version older IE 5
        }
    }                                                // End setup Ajax.
    if (ajax==null) {                                // If we couldn't initialize Ajax...
        alert("Your browser doesn't support AJAX.");  // Sorry msg.
        return false                                  // Return false, couldn't set up ajax
    }
    return ajax;
}


function compruebaUsuario(usuario,mensajeRequerido,mensajeCorto,mensajeExiste,mensajeNoExiste,jsessionid) {
  
    var inputUser = document.getElementById("mensajeUsuario");
    if(usuario.length==0){
        inputUser.innerHTML=mensajeRequerido;
        nombreok = false;//Incorrecto el campo
    }else if(usuario.length<5){
        inputUser.innerHTML=mensajeCorto;
        nombreok = false;//Incorrecto el campo
    }else{
        var ajax = ajaxInit();
        ajax.onreadystatechange= function () {
            if (ajax.readyState==4 || ajax.readyState=="complete") { //  see if the complete flag is set.
                if (ajax.status==200) {  //  see if the response is correct.
                    //alert("modificar la capa correspondiente");
                    var existe = ajax.responseText;             // Get the response of our server
                    if (existe=="true") {
                        inputUser.innerHTML=mensajeExiste;
                        nombreok = false;//Incorrcto el campo
                    } else {
                        inputUser.innerHTML=mensajeNoExiste;
                        nombreok = true;//Correcto el campo
                    }
                    validarSubmit();
                }
            }
        }
        ajax.open("GET","ExisteUsuario;jsessionid="+jsessionid+"?usuario="+usuario,true);
        ajax.send(null);
    }
//validarSubmit();    
}

function compruebaContrasena(password,mensajeCorto) {  
    var inputPass = document.getElementById("mensajeClave");
    if(password.length<5){
        inputPass.innerHTML=mensajeCorto;
        passok = false;//Incorrecto el campo
    }else{
        inputPass.innerHTML='';
        passok = true;//Correcto el campo
    }
//validarSubmit();       
}

function compruebaRecontrasena(pass,repass,mensajeCorto,mensajeDiferentes,mensajeIguales) {                  
    var inputRepass=document.getElementById("mensajeReclave");
    if(repass.length<5){
        inputRepass.innerHTML=mensajeCorto;
        repassok = false;//Incorrecto el campo
    }else if(pass!=repass){
        inputRepass.innerHTML=mensajeDiferentes;
        repassok = false;//Incorrecto el campo
    }else{
        inputRepass.innerHTML=mensajeIguales;
        repassok=true;//Correcto el campo
    }
//validarSubmit();
}

function esMail(texto){
  
    var mailres = true;
    var cadena = "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ1234567890@._-";
  
    var arroba = texto.indexOf("@",0);
    if ((texto.lastIndexOf("@")) != arroba) arroba = -1;
  
    var punto = texto.lastIndexOf(".");
  
    for (var contador = 0 ; contador < texto.length ; contador++){
        if (cadena.indexOf(texto.substr(contador, 1),0) == -1){
            mailres = false;
            break;
        }
    }
  
    if ((arroba > 1) && (arroba + 1 < punto) && (punto + 1 < (texto.length)) && (mailres == true) && (texto.indexOf("..",0) == -1))
        mailres = true;
    else
        mailres = false;
  
    return mailres;
} 

function compruebaEmail(email, capaEmail, mensajeOk, mensajeNoOk,mensajeEmailEnUso,jsessionid,idUsuario) {  
    emailok = esMail(email);
    if (!emailok) {
        capaEmail.innerHTML=mensajeNoOk;
    } else {
        emailok = false;
        var ajax = ajaxInit();
        ajax.onreadystatechange= function () {
            if (ajax.readyState==4 || ajax.readyState=="complete") { //  see if the complete flag is set.
                if (ajax.status==200) {  //  see if the response is correct.
                    var existe = ajax.responseText;             // Get the response of our server
                    if (existe=="false" || (idUsuario!=null && idUsuario==existe)) {
                        capaEmail.innerHTML=mensajeOk;
                        emailok = true;//Correcto el campo
                    //alert("(asignacion) CompruebaEmail emailok="+emailok);
                    } else {
                        capaEmail.innerHTML=mensajeEmailEnUso;
                        emailok = false;//Incorrcto el campo
                    //alert("(asignacion) CompruebaEmail emailok="+emailok);
                    }
                    validarSubmit();
                }
            }
        }
        ajax.open("GET","ExisteCorreoAjax;jsessionid="+jsessionid+"?email="+email,true);
        ajax.send(null);
    }
}


function validarSubmit() {
    
    var todook=passok&&repassok&&nombreok&&emailok;
    if (todook) {
        encriptar_registro();
    }
} 
/*
Los parametros de la funcion son:
Los valores que vamos a comprobar (Texto introducido por el usuario)
La capa que muestra el mensaje de error del correo.
Texto de los mensajes de errores.
 */
function comprobarValoresRegistro(campoUsuario,campoClave,campoReclave,campoEmail,capaEmail,mensajeExiste,mensajeCorto,mensajeDiferentes,mensajeNoCorrecto,mensajeRequerido,jsessionid) {
    compruebaUsuario(campoUsuario,mensajeRequerido,mensajeCorto,mensajeExiste,"",jsessionid);
    compruebaContrasena(campoClave,mensajeCorto);
    compruebaRecontrasena(campoClave,campoReclave,mensajeCorto,mensajeDiferentes,"");
    compruebaEmail(campoEmail, capaEmail, "", mensajeNoCorrecto,mensajeExiste,jsessionid,null);
//validarSubmit(); Se realiza en los ajaxs, ya que no sabemos cual termina antes.
}

/*Funcion que se llama en la modificacion de los datos basico del usuario
 *Los parametros de la funcion son:
 *Los valores que vamos a comprobar (Texto introducido por el usuario)
 *La capa que muestra el mensaje de error del correo.
 *Texto de los mensajes de errores.
 */
function modificarDatosUsuario(idUsuario,campoClave,campoReclave,campoEmail,capaEmail,mensajeCorto,mensajeDiferentes,mensajeNoCorrecto,mensajeEmailEnUso,jsessionid) {    
    if (campoClave.length>0 || campoReclave.length>0) {
        compruebaContrasena(campoClave,mensajeCorto);
        compruebaRecontrasena(campoClave,campoReclave,mensajeCorto,mensajeDiferentes,"");
    } else if(campoClave.length==0 && campoReclave.length==0){
        passok = true;
        repassok = true;
        document.getElementById("mensajeClave").innerHTML = "";
        document.getElementById("mensajeReclave").innerHTML = "";
    }
    nombreok = true;
    compruebaEmail(campoEmail, capaEmail, "", mensajeNoCorrecto,mensajeEmailEnUso,jsessionid,idUsuario);
//validarSubmit(); Se realiza en el ajax, ya que a veces seguia por aqui y el ajax no habia terminado 
}

//idDiv   El identificador de la capa que se oculta 
//idInput El identificador del input type=text el cual el usuario escribira
//idHidden El identificador del input type=hidden el cual se guarda el identificador del elemento seleccionado
//url El Servlet el cual se realizara la peticion, se le agregara al final la cadena del input type=text
//Nota el servlet tiene que devolver un Json con la siguiente estructura
//{"combobox":[{"nombre":"hola David","id":16},{"nombre":"adios David","id":17},{"nombre":"buenos dias David","id":18}]}
//Nota el input type=text tiene que llamar a esta funcion cada vez que se pulse una tecla, propiedad es onkeyup="buscarComboBox(param1,param2,param3,param4);"
function buscarComboBox(idDiv,idInput,idHidden,url) { 
    var div = document.getElementById(idDiv);
    var hidden = document.getElementById(idHidden);
    var input = document.getElementById(idInput);
    var cadena = input.value;
    //alert('tag a buscar: '+cadena);
    if (cadena.length >= 3) { //Si son mas de tres caracteres realizar la busqueda
        var ajax = ajaxInit();
        ajax.onreadystatechange= function () {
            if (ajax.readyState==4 || ajax.readyState=="complete") { //  see if the complete flag is set.
                if (ajax.status==200) {  //  see if the response is correct.
          
                    var palabras = eval("(" + ajax.responseText + ")");// Get the response of our server
                    //alert('palabras.length: '+palabras.length);
                    //alert('palabras.combobox: '+palabras.combobox);
                    //alert('palabras.combobox.length: '+palabras.combobox.length);
                    //alert('palabras.combobox[0].id: '+ palabras.combobox[0].id);
          
                    var num_pal = palabras.combobox.length;
          
                    hidden.value=-1;
          
                    //Mostrar todas las posibilidades
                    div.innerHTML="";
                    div.style.visibility = "visible";
                    for (i=0;i<num_pal;i++) {
                        if(palabras.combobox[i].nombre.toUpperCase() == cadena.toUpperCase()){//Si existe uno exactamente igual se asigna al campo oculto
                            hidden.value = palabras.combobox[i].id;
                        }
                        div.innerHTML+="<a href='#' onclick=\"seleccionarComboBox('"+idDiv+"','"+idInput+"','"+palabras.combobox[i].nombre+"','"+idHidden+"','"+palabras.combobox[i].id+"');return false;\"> "+palabras.combobox[i].nombre+"</a><br/>";
                    }
          
                }
            }
        }
        ajax.open("GET",url+escape(cadena),true);
        ajax.send(null);
    } else {//Por haber menos de tres letras,se deshabilita todo.
        hidden.value=-1;
        div.innerHTML="";
        div.style.visibility = "hidden";
    }
}

function seleccionarComboBox(idDiv,idInput,valorInput,idHidden,valorHidden) {
    document.getElementById(idInput).value=valorInput;
    document.getElementById(idHidden).value=valorHidden;
    document.getElementById(idDiv).innerHTML="";//Al seleccionar un elemento desaparece el desplegable.
    document.getElementById(idDiv).style.visibility = "hidden";
}

function buscarComboBoxVerDatos(idDiv,idInput,id_session,url) { 
    var div = document.getElementById(idDiv);
    var input = document.getElementById(idInput);
    var cadena = input.value;
    //alert('tag a buscar: '+cadena);
    if (cadena.length >= 3) { //Si son mas de tres caracteres realizar la busqueda
        var ajax = ajaxInit();
        ajax.onreadystatechange= function () {
            if (ajax.readyState==4 || ajax.readyState=="complete") { //  see if the complete flag is set.
                if (ajax.status==200) {  //  see if the response is correct.
          
                    var palabras = eval("(" + ajax.responseText + ")");// Get the response of our server
                    //alert('palabras.length: '+palabras.length);
                    //alert('palabras.combobox: '+palabras.combobox);
                    //alert('palabras.combobox.length: '+palabras.combobox.length);
                    //alert('palabras.combobox[0].id: '+ palabras.combobox[0].id);
          
                    var num_pal = palabras.combobox.length;
         
                    //Mostrar todas las posibilidades
                    div.innerHTML="";
                    div.style.visibility = "visible";
                    for (i=0;i<num_pal;i++) {
                        if(palabras.combobox[i].nombre.toUpperCase() == cadena.toUpperCase()){//Si existe uno exactamente igual se asigna al campo oculto
                            
                        }
                        div.innerHTML+="<a class='enlace_negro' href='#' onclick=\"crearCapa('Control;jsessionid="+id_session+"?accion=ver&amp;idp="+palabras.combobox[i].id+"');return false;\"> &sdot;"+palabras.combobox[i].nombre+"</a><br/>";
                    }
          
                }
            }
        }
        ajax.open("GET",url+escape(cadena),true);
        ajax.send(null);
    } else {//Por haber menos de tres letras,se deshabilita todo.
        div.innerHTML="";
        div.style.visibility = "hidden";
    }
}

function EvaluarAJAX(idp,idu,v,idCurrent,jsessionid) {
    /*var liCurrent = document.getElementById(idCurrent);
    var estadoFavorito=document.getElementById('estado_favorito_'+idp);
    
    if(estadoFavorito.value==1){
        FavoritoAjax(idp,idu,0,'favorito_'+idp, idCurrent,jsessionid);
    }
    
    var ancho=0;
    switch(v){
        case -4:
            ancho=12;
            break;
        case -3:
            ancho=25;
            break;
        case -2:
            ancho=37;
            break;
        case -1:
            ancho=50;
            break;
        case 0:
            ancho=75;
            break;
        case 1:
            ancho=87;
            break;
        case 2:
            ancho=100;
            break;
        case 3:
            ancho=112;
            break;   
        case 4:
            ancho=125;
            break;
    }*/
    var ajax = ajaxInit();
    ajax.onreadystatechange= function () {
        if (ajax.readyState==4 || ajax.readyState=="complete") { //  see if the complete flag is set.
            if (ajax.status==200) {  //  see if the response is correct.
                var ok = ajax.responseText;             // Get the response of our server
                if (ok=="true") {
                    //liCurrent.style.width=""+ancho+"px";
                    CalculoPuntuacion(jsessionid);
                } else {
        
            }
            }
        }
    }
    ajax.open("GET","EvaluarServlet;jsessionid="+jsessionid+"?idp="+idp+"&idu="+idu+"&v="+v,true);
    ajax.send(null);
}

function FavoritoAjax(idp,idu,v,idCurrentF, idCurrentE,jsessionid) {   
    /*var liCurrentF = document.getElementById(idCurrentF);
    var idCurrentFTXT="'"+idCurrentF+"'";
    var idCurrentETXT="'"+idCurrentE+"'";
    var liCurrentE = document.getElementById(idCurrentE);*/
    var ajax = ajaxInit();
    ajax.onreadystatechange= function () {
        if (ajax.readyState==4 || ajax.readyState=="complete") { //  see if the complete flag is set.
            if (ajax.status==200) {  //  see if the response is correct.
                var ok = ajax.responseText;             // Get the response of our server
                //no tenemos en cuenta respuesta del server
                /*if (v==1) {
                    liCurrentF.innerHTML = '<a class="favorito" href="#" onclick="javaScript:FavoritoAjax('+idp+','+idu+',0, '+idCurrentFTXT+', '+idCurrentETXT+',\''+jsessionid+'\');return false;">'+
                        '<img class="favorito" src="resources/favorito1.gif" width="19" height="19" /></a>';
                    liCurrentE.style.width="125px";
                    document.getElementById('estado_favorito_'+idp).value=1;
                }else { 
                    liCurrentF.innerHTML = '<a class="favorito" href="#" onclick="javaScript:FavoritoAjax('+idp+','+idu+',1, '+idCurrentFTXT+', '+idCurrentETXT+',\''+jsessionid+'\');return false;">'+
                        '<img class="favorito" src="resources/favorito0.gif" width="19" height="19" /></a>';
                    liCurrentE.style.width="125px";
                    document.getElementById('estado_favorito_'+idp).value=0;
                }*/
                CalculoPuntuacion(jsessionid);
            }
        }
    }
    ajax.open("GET","FavoritoServlet;jsessionid="+jsessionid+"?idp="+idp+"&idu="+idu+"&f="+v,true);
    ajax.send(null);
}

function CalculoPuntuacion(jsessionid) {   

    var ajax = ajaxInit();
    ajax.onreadystatechange= function () {
        if (ajax.readyState==4 || ajax.readyState=="complete") { //  see if the complete flag is set.
            if (ajax.status==200) {  //  see if the response is correct.
                var ok = ajax.responseText;             // Get the response of our server
            //no tenemos en cuenta respuesta del server
            }
        }
    }
    ajax.open("GET","PuntuarServlet;jsessionid="+jsessionid,true);
    ajax.send(null);
}


function cambiarEstrellas(idCorazon,id1estrella,id2estrella,id3estrella,id4estrella,id5estrella,imagenEstrellaApagado,imagenEstrellaEncendida,imagenCorazonApagado,nivel){
    var corazon = document.getElementById(idCorazon);
    var estrella1 = document.getElementById(id1estrella);
    var estrella2 = document.getElementById(id2estrella);
    var estrella3 = document.getElementById(id3estrella);
    var estrella4 = document.getElementById(id4estrella);
    var estrella5 = document.getElementById(id5estrella);
    if (nivel<6) {//Si pincha en estrella a pagar corazon, si pincha en corazon (nivel=6) no tratar corazon
        corazon.src = imagenCorazonApagado;//si pulsa cualquier estrella ya no es favorito
    }
    estrella1.src = imagenEstrellaEncendida;//Siempre sera 1 o mayor.
    if (nivel>=2) {
        estrella2.src = imagenEstrellaEncendida;
    } else {
        estrella2.src = imagenEstrellaApagado;
    }
    if (nivel>=3) {
        estrella3.src = imagenEstrellaEncendida;
    } else {
        estrella3.src = imagenEstrellaApagado;
    }
    if (nivel>=4) {
        estrella4.src = imagenEstrellaEncendida;
    } else {
        estrella4.src = imagenEstrellaApagado;
    }
    if (nivel>=5) {
        estrella5.src = imagenEstrellaEncendida;
    } else {
        estrella5.src = imagenEstrellaApagado;
    }
}

function cambiarCorazon(idCorazon,id1estrella,id2estrella,id3estrella,id4estrella,id5estrella,imagenEstrellaApagado,imagenEstrellaEncendida,imagenCorazonApagado,imagenCorazonEncendido){
    var corazon = document.getElementById(idCorazon);
    if (corazon.src.indexOf(imagenCorazonEncendido)==-1) {
        corazon.src = imagenCorazonEncendido;
    } else {
        corazon.src = imagenCorazonApagado;
    }
    //tanto si marca como si desmarca el favorito encender las 5 estrellas
    cambiarEstrellas(idCorazon,id1estrella,id2estrella,id3estrella,id4estrella,id5estrella,imagenEstrellaApagado,imagenEstrellaEncendida,imagenCorazonApagado,6);
}

/**
 * Almacena Tag
 */
function almacenaTag(divTop, jsessionid, idp) {
    var texto = document.getElementById("nombreTag").value;
    var ajax;
    ajax = ajaxInit();
    ajax.onreadystatechange = function(){
        if (ajax.readyState==4 || ajax.readyState=="complete") { //  see if the complete flag is set.
            if (ajax.status==200) {  //  see if the response is correct.
                document.getElementById(divTop).innerHTML = 'Etiqueta agregada';
            }
        }
    }
    ajax.open("GET", "AgregarMisTags;jsessionid=" + jsessionid + "?idp=" + idp + "&nombreTag=" + texto + "&dentro=ok", true);
    ajax.send(null);
}

//
///**
// * Carga la pestaña del top programas
// */
//function cargaTop(divTop, jsessionid) {
//  var ajax;
//  ajax = ajaxInit();
//  ajax.onreadystatechange = function(){
//    if (ajax.readyState==4 || ajax.readyState=="complete") { //  see if the complete flag is set.
//      if (ajax.status==200) {  //  see if the response is correct.
//        document.getElementById(divTop).innerHTML = ajax.responseText;
//      }
//    }
//  }
//  ajax.open("GET", "newTopProgramasServlet;jsessionid=" + jsessionid, true);
//  ajax.send(null);
//}
//
///**
// * Carga la pestaña de recomendaciones
// */
//function cargaRec(divTop, jsessionid) {
//  var ajax;
//  ajax = ajaxInit();
//  ajax.onreadystatechange = function(){
//    if (ajax.readyState==4 || ajax.readyState=="complete") { //  see if the complete flag is set.
//      if (ajax.status==200) {  //  see if the response is correct.
//        document.getElementById(divTop).innerHTML = ajax.responseText;
//      }
//    }
//  }
//  ajax.open("GET", "newRecomendacionesServlet;jsessionid=" + jsessionid, true);
//  ajax.send(null);
//}
//
///**
// * Carga la pestaña de parrilla recomendados
// */
//function cargaParRec(divTop, jsessionid) {
//  var ajax;
//  ajax = ajaxInit();
//  ajax.onreadystatechange = function(){
//    if (ajax.readyState==4 || ajax.readyState=="complete") { //  see if the complete flag is set.
//      if (ajax.status==200) {  //  see if the response is correct.
//        document.getElementById(divTop).innerHTML = ajax.responseText;
//        //document.getElementById("left1").onmouseover=moveleftCom();
//        //document.getElementById("right1").onclick=moverightCom();
//        //moverParrillaCom('tarde');
//        //scrollV();
//
//        alert("2");
//      }
//    }
//  }
//    ajax.open("GET", "newInicioServlet;jsessionid=" + jsessionid, true);
//    ajax.send(null);
//  }
//
//  /**
// * Carga la pestaña de la parrilla completa
// */
//  function cargaParCom(divTop, jsessionid) {
//    var ajax;
//    ajax = ajaxInit();
//    ajax.onreadystatechange = function(){
//      if (ajax.readyState==4 || ajax.readyState=="complete") { //  see if the complete flag is set.
//        if (ajax.status==200) {  //  see if the response is correct.
//          document.getElementById(divTop).innerHTML = ajax.responseText;
//        }
//      }
//    }
//    ajax.open("GET", "newVerUnCanal;jsessionid=" + jsessionid, true);
//    ajax.send(null);
//  }





