var tbody;
var idANS = 0;
var i = 1;
var show;
var columna = 0;
var orden = 1;


function init(){
    try
    {
    
	}catch(e){
		mostrarErrorAplicacion("Error en la inicialización de la página", e.message);
    }
}

function provincias(){
    try{
        if($("cbopaisres").value!="1")
        {

            $("cboprovinciares").disabled=true;
        }
        else
        {
            $("cboprovinciares").disabled=false;
        }
            
	}catch(e){
		mostrarErrorAplicacion("Error a la hora de limpiar los filtros", e.message);
    }
}

function ordenarLineas(obj)
{
    try{
        var js_args = "OrdenarLineas@@";
        
        switch(obj.innerHTML)
        {
            case "Fecha":
                columna = 0;
                orden = 0;
                break;
            case "Perfil":
                columna = 1;
                orden = 0;
                break;
            case "Provincia":
                columna = 2;
                orden = 0;
                break;
            case "Vacantes":
                columna = 3;
                orden = 0;
                break;
            case "C.Principal":
                columna = 4;
                orden = 0;
                break;    
            case "Responsabilidades y funciones":
                columna = 5;
                orden = 0;
                break;
            default:
                if(orden == 0)
                    orden = 1;
                else
                    orden = 0;
                break; 
        }
        
        for(var i=0; i<6; i++)
        {
            if(i==columna)
                if(orden == 1)
                    $("tblCabecera").rows[0].children[i].innerHTML =  $("tblCabecera").rows[0].children[i].id + " &#9660;";
                else
                    $("tblCabecera").rows[0].children[i].innerHTML =  $("tblCabecera").rows[0].children[i].id + " &#9650;";
            else
                $("tblCabecera").rows[0].children[i].innerHTML =  $("tblCabecera").rows[0].children[i].id;
        }
                
        js_args += columna+"@@"+orden;
        /*js_args += Columna+"@@";
        js_args += Orden;*/
        RealizarCallBack(js_args,"");  //con argumentos
    }catch(e){
		mostrarErrorAplicacion("Error al ordenar las ofertas", e.message);
    } 

}



function altaPrecandidato(){
    
    try{
        var strAux = "";
    
        //CAMPO SEXO
        if($("rdbsexo_0").checked)
            $("hdnsexo").value = "M";
        else
            $("hdnsexo").value = "H";
        
        //CAMPO NOMBRE
        if($("txtnombre").value == "")
        {
            strAux += "txtnombre@@";
            $("lblerrorNom").style.display = "block";   
        }
        else
        {
            $("hdnnombre").value = $("txtnombre").value;
            $("lblerrorNom").style.display = "none";  
            pintarBlancos($("txtnombre"));
        }
        
        //CAMPO APELLIDO1
        if($("txtapellido1").value == "")
        {
            strAux += "txtapellido1@@";
            $("lblerrorApe").style.display = "block";   
        }
        else
        {
            $("hdnapellido1").value = $("txtapellido1").value;
            $("lblerrorApe").style.display = "none";   
            pintarBlancos($("txtapellido1"));
        }
        
        //CAMPO APELLIDO2        
        $("hdnapellido2").value = $("txtapellido2").value;
        //CAMPOS PAIS
        $("hdnpais").value = $("cbopaisres").value;
        //CAMPO PROVINCIA
        $("lblerrorProv").style.display = "none";
        if($("cbopaisres").value == "1" && $("cboprovinciares").value == "0")
        {
            strAux += "cboprovinciares@@";
            $("lblerrorProv").style.display = "block";
        }
        else
        {
            $("hdnprovincia").value = $("cboprovinciares").value;
            pintarBlancos($("cboprovinciares"));
        } 
        
        //CAMPO TELEFONO
        
        $("lblerrortlf1").style.display = "none";
        $("lblerrortlf2").style.display = "none";
        
        if($("txttelefono").value == "")
        {
            strAux += "txttelefono@@";
            $("lblerrortlf1").style.display = "block";     
        }
        else if (!EsNumerico($("txttelefono").value))
        {
            strAux += "txttelefono@@";
            $("lblerrortlf2").style.display = "block"; 
        }
        else
        {
            $("hdntelefono").value = $("txttelefono").value;
            pintarBlancos($("txttelefono"));
        }
        
        //CAMPO EMAIL
        $("lblerrormail1").style.display = "none";
        $("lblerrormail2").style.display = "none";
        
        if($("txtmail").value == "")
        {
            strAux += "txtmail@@";
            $("lblerrormail1").style.display = "block";
        } 
        else if (!chkEmail($("txtmail").value))
        {
            strAux += "txtmail@@";
            $("lblerrormail2").style.display = "block";
        }
        else
        {
            $("hdnemail").value = $("txtmail").value;
            pintarBlancos($("txtmail"));
        }
        
        //CAMPO FECHANACI
        /*if ($("cbodd").value==" " || $("cbomm").value ==" " || $("cboaaaa").value ==" ")*/
        if ($("cbodd").value=="" || $("cbomm").value =="" || $("cboaaaa").value =="")
        {
            strAux += "cboaaaa@@cbomm@@cbodd@@";
            $("lblerrorFec1").style.display = "block";
            $("lblerrorFec2").style.display = "none";
        }
        else if(!validarFecha($("cbodd").value,$("cbomm").value,$("cboaaaa").value))
        {
            strAux += "cboaaaa@@cbomm@@cbodd@@";
            $("lblerrorFec1").style.display = "none";
            $("lblerrorFec2").style.display = "block";
        }
        else
        {
            $("hdnfecnaci").value = $("cbodd").value +"/"+$("cbomm").value+"/"+$("cboaaaa").value
            $("lblerrorFec1").style.display = "none";
            $("lblerrorFec2").style.display = "none";
            pintarBlancos($("cbodd"));
            pintarBlancos($("cbomm"));
            pintarBlancos($("cboaaaa"));
        }
        
        
        //CAMPO NIF
        
        $("lblerrornif1").style.display = "none";
        $("lblerrornif2").style.display = "none";
        
        var DNI = $("txtnif").value.replace(/^\s+|\s+$/g, '') ; 
        
        if(DNI=="")
        {
            strAux += "txtnif@@";
            $("lblerrornif1").style.display = "block";    
        }
        else if(($("rdbDocumento_0").checked && !validarNIF($("txtnif").value)))
        {
            strAux += "txtnif@@";
            $("lblerrornif2").style.display = "block";
        }
        else
        {
            $("hdnNIF").value = $("txtnif").value;
            pintarBlancos($("txtnif"));
        }
        
        if($("fupdocumento").value == "")
        {
            strAux += "fupdocumento@@";
            $("lblerrorCV").style.display = "block";    
        }
        else
        {
            pintarBlancos($("fupdocumento"));
            $("lblerrorCV").style.display = "none";   
        }
        
        $("hdnobserva").value = $("txtobservaciones").value;       
    
		var theform = document.forms["aspnetForm"];
		if(strAux=="")
		{
            //$("divEnviando").style.display='';
            //showEnviando(0);
            //$("btnEnviar").onclick='';
            $("tblPresentado").style.visibility='hidden';
            theform.submit();
            //$("divbtnenviar").style.display="none";
            //$("divform").style.display="none";
            //$("divEnviando").style.display="block";
        }
        else
            pintarCampos(strAux.substr(0,strAux.length-2));   
	}catch(e){
		mostrarErrorAplicacion("Error al validar el fichero de carga", e.message);
    }
}
function Inscribir()
{
    altaPrecandidato();
    //__doPostBack("","");
}
function showEnviando(valor)
{
    if(valor != 100)
    {
        valor=valor+2;
        $("divEnviando").style.opacity = valor/100;
        $("divEnviando").style.filter = 'alpha(opacity=' + valor + ')';
        t=setTimeout('showEnviando('+valor+')',5);
    }
}

function pintarCampos(campos)
{
    try
    {  
        var aCampos = new Array();
        aCampos = campos.split("@@");
        for(obj in aCampos)
        {
            $(aCampos[obj]).style.border = "1px solid red";
            $(aCampos[obj]).style.backgroundColor = "#e78888";
        }
    }catch(e){
		mostrarErrorAplicacion("Error a la hora mostrar los campos incorrectos", e.message);
    }
}

function pintarBlancos(obj)
{
    obj.style.backgroundColor = "white";
    obj.style.border = "1px solid #00698C";
}

function validarFecha(day,month,year)
{  
    var objDate;
    var mSeconds;
    
    if(day.length==1)
        day = "0"+day;
    if(month.length==1)
        month = "0"+(month-1);
    else
        month = (month-1);
            
    mSeconds = (new Date(year, month, day)).getTime();  
    objDate = new Date();  
    objDate.setTime(mSeconds);  

    // Si no existe coincidencia la funcion devolverá false
    if (objDate.getFullYear() != year)  return false;  
    if (objDate.getMonth()    != month) return false;  
    if (objDate.getDate()     != day)   return false;  
    
    // Si todo coincide
    return true;  
}

function validarNIF(dni)
{
    if(dni.substr(0,1)=="X")
        dni = dni.substr(1,dni.length-1)
    numero = dni.substr(0,dni.length-1);
    let = dni.substr(dni.length-1,1).toUpperCase();
    numero = numero % 23;
    letra='TRWAGMYFPDXBNJZSQVHLCKET';
    letra=letra.substring(numero,numero+1);
    if (letra!=let) 
        return false;
    else
        return true;
}

function chkEmail(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    return false
		 }
		 if (str.indexOf(dot,0)==str.length-1){
		    return false
		 }
		 if (str.indexOf(" ")!=-1){
		    return false
		 }
 		 return true					
	}
	
	function EsNumerico(str)
   {
   var strValidChars = "0123456789.-+()";
   var strChar;

   if (str.length == 0) return false;

   for (i = 0; i < str.length ; i++)
      {
      strChar = str.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         return false;
         }
      }
   return true;
   }
   
   
   
function MostrarTool(desc){
    try
    {
        $("divFondoTooltip").innerHTML = desc;
        $("divDescripcion").innerHTML = desc;
	}catch(e){
		mostrarErrorAplicacion("Error MostrarTool", e.message);
    }
}
   
function ToolTipMov(e)
{
    Coordenadas = getPosition(e);
    if(Coordenadas.x+590>document.body.clientWidth)
        Coordenadas.x = document.body.clientWidth - 590;
    $("divToolTip").style.left = (Coordenadas.x+15)+"px";
    $("divToolTip").style.top = (Coordenadas.y+15)+"px";        
}

function getPosition(e) 
{
    if (!e) e = window.event;
    var cursor = {x:0, y:0};
    
    if (e.pageX || e.pageY) 
    {
        cursor.x = e.pageX;
        cursor.y = e.pageY;
    }
    else 
    {
        cursor.x = e.clientX +
        (document.documentElement.scrollLeft ||
        document.body.scrollLeft) -
        document.documentElement.clientLeft;
        cursor.y = e.clientY +
        (document.documentElement.scrollTop ||
        document.body.scrollTop) -
        document.documentElement.clientTop;
    }
    return cursor;
}

var nfi = 0; //número fila inicio
var nff = 0; //número fila fin
var nfo = 0; //número fila original
var nfs = 0; //número filas seleccionadas
function mm(oFila,e)
{	
    try{
	    var oTabla = $("tblLineas");
	    var nFila  = oFila.rowIndex;

	    if (e.ctrlKey){  //Tecla control pulsada
       		var j=0;
		    for (var i=0;i < oTabla.rows.length; i++){
		        if (oTabla.rows[i].style.display == "none") continue;
		        if (i == nFila) break;
		        j++;
		    }

	        if (oFila.className == "filaSel"){
	            if (nfs > 1){
	                nfs--;
			        if (j % 2 == 0)
				        oFila.className = "filaImpar";
			        else
				        oFila.className = "filaPar";
	            }
	        }else{
	            nfs++;
	            oFila.className = "filaSel";
	            iFila = oFila.rowIndex;
	        }
	    }else if (e.shiftKey){	//Tecla shift pulsada
		    var nff = nFila;
		    if (nfo > nff){
			    nff = nfo;
			    nfi = nFila;
		    }
		    if (nfi < nfo) nff = nfo;
		    if (nFila > nfo){
		        nfi = nfo
		        nff = nFila;
		    }
    		var j=0;
		    for (var i=0;i < oTabla.rows.length; i++){
		        if (oTabla.rows[i].style.display == "none") continue;
		        if (i >= nfi && i <= nff){	
				    if (oTabla.rows[i].className != "filaSel"){
				        nfs++;
				        iFila = i;
					    oTabla.rows[i].className = "filaSel";				
				    }
			    }else{
			        if (oTabla.rows[i].className == "filaSel") nfs--;

			        if (j % 2 == 0)
				        oTabla.rows[i].className = "filaImpar";
			        else
				        oTabla.rows[i].className = "filaPar";
			    }
			    j++;
		    }
	    }
	    else{  //teclas ni control ni shift pulsadas.
	        var j=0;
		    for (var i=0;i < oTabla.rows.length; i++){
		        if (oTabla.rows[i].style.display == "none") continue;
                if (i == nFila){
                    nfo = i;
                    nfi = i;
                    nff = i;
        	        if (oFila.className != "filaSel"){
	                    nfs++;
	                    iFila = i;
	                    oFila.className = "filaSel";
	                }
			    }else{
			        if (oTabla.rows[i].className == "filaSel") nfs--;

			        if (j % 2 == 0)
				        oTabla.rows[i].className = "filaImpar";
			        else
				        oTabla.rows[i].className = "filaPar";
                }
			    j++;
		    }
	    }
	}catch(e){
		mostrarErrorAplicacion("Error en la selección múltiple", e.message);
    }
}


function RespuestaCallBack(strResultado, context){
    try
    {
        var aResul = strResultado.split("@@");
        if (aResul[1] != "OK"){
            //restaurarFilasInvisibles("tblDatos");
            ocultarProcesando();
            var reg = /\\n/g;
            var sError=aResul[2];
		    var iPos=sError.indexOf("integridad referencial");
		    if (iPos>0){
		        alert("No se puede eliminar la tabla '"+aResul[3]+"',\n ya que existen elementos con los que está relacionada.");
		    }
		    else alert(sError.replace(reg,"\n"));
        }else
        {
            switch (aResul[0]){
                case "OrdenarLineas":
                    //alert("respuesta");
                    $("divContainer").innerHTML = aResul[2];
			        break;				                    
            }
        }
	}
	catch (e)
	{
        mostrarErrorAplicacion("Error en la función RespuestaCallBack", e.message);	
	}    	    
}

function DetalleLinea(fila)
{
    
    //var id=$("tblLineas").rows[fila].cells[0].innerHTML;
    var id=$("tblLineas").rows[fila].getAttribute("codlin");
    location.href="oferta.aspx?codlin="+id;
}


function MostrarFormulario()
{
    try
    {
        var oTabla = $("tblLineas");
        
        for(var i=0; i < oTabla.rows.length; i++)
        {
            if(oTabla.rows[i].className == "filaSel")
                $("hdnLineas").value += oTabla.rows[i].id + ",";
        }
        if($("hdnLineas").value != "")
        {
            $("hdnLineas").value.substr(0,$("hdnLineas").value.length-1);
            $("divformulario").style.display = "block";
            FondoOscurecido("Mostrar");
        }
                    
	}catch(e){
		mostrarErrorAplicacion("Error al mostrar el formulario", e.message);
    }   
}
function ocultarForm()
{
    try
    {
        $("divformulario").style.display = "none";
        FondoOscurecido("ocultar");
        $("hdnLineas").value = "";   
	}
	catch (e)
	{
        mostrarErrorAplicacion("Error en la función ocultarForm", e.message);	
	}    	 
}

//Muestra u oculta el mensaje radical (Todo el fondo de pantalla oscurecido)
var indexElemento=-1;//variable para guardar el indice del objeto donde lanzas el iframe
function FondoOscurecido(accion) 
 {
    if(accion == "ocultar")
        {
//            if (document.all[indexElemento].style.visibility!="hidden")
//                document.all[indexElemento].focus();//restauramos el foco con el proposito de recuperar el scroll predido
            document.getElementById("divCortina").style.display='none';
            document.body.scroll="yes";
        }
        
    else
        {                                
            //indexElemento=window.document.activeElement.sourceIndex;//guardamos el indice del objeto en la variable
            var medidas = obtenerMedidasPantalla();  
            //window.scrollTo(0,0);
            document.getElementById("divCortina").style.width=screen.width-21;
            document.getElementById("divCortina").style.height= medidas[5];//;screen.availHeight
            document.getElementById("divCortina").style.display='block';   
             
             if (medidas[0]<medidas[4])
                    {   
                       document.body.scroll="yes";                                                
                    } 
                else
                    {
                        document.body.scroll="no";                                    
                    }                 
        }
 }
 
 //Función que obtiene diferentes medidas dependiendo de la resolución de pantalla que tengas configurada en ese momento. 
 function obtenerMedidasPantalla(){

    var widthViewport,heightViewport,xScroll,yScroll,widthTotal,heightTotal;
    
    if (typeof window.innerWidth != 'undefined')
    {

        widthViewport= window.innerWidth-17;
        heightViewport= window.innerHeight-17;
    }
    else if(typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth !='undefined' && document.documentElement.clientWidth != 0)
    {

        widthViewport=document.documentElement.clientWidth;
        heightViewport=document.documentElement.clientHeight;
    }
    else
    {

        widthViewport= document.getElementsByTagName('body')[0].clientWidth;
        heightViewport=document.getElementsByTagName('body')[0].clientHeight;
    }

    xScroll=self.pageXOffset || (document.documentElement.scrollLeft+document.body.scrollLeft);
    yScroll=self.pageYOffset || (document.documentElement.scrollTop+document.body.scrollTop);
    widthTotal=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth,widthViewport);
    heightTotal=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight,heightViewport);
    
    //alert(widthViewport + " " + heightViewport + " " + xScroll + " " + yScroll + " " + widthTotal + " " + heightTotal);
    return [widthViewport,heightViewport,xScroll,yScroll,widthTotal,heightTotal];
    

}

