var codigoAviso="";
var idAvisoLigthBox="";
var ofertaFecha="";
var characterEncoding="UTF-8";
var ori="";
var tipoCargoTXT="";
var regionTXT="";
var usersSeleccionados = new Array();
var usersDesSeleccionados = new Array();
var paramAll = 0;
var siteGestionRaizJs = "http://gestion.laborum.cl";
var industryRRHH = ["17","30","47","53"];


/*****VALIDA CADENAS ALFABETICAS*****/
var alfabetico=/^[a-zA-Z \s áéíóúÁÉÍÓÚÑñüöÜÖÇÆÈÀæç]+$/;

var numerico= /^[0-9]+$/;
var alfanumerico = /^[\w \s áéíóúÁÉÍÓÚÑñüöÜÖ][^&#<>?¿]+$/;
var emailtype =/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var urltype =/^((ht|f)tp(s?)\:\/\/){0,1}[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)( [a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$/;

var recargarPagina="";
reloadPage= function(){  //llamada en modalbox.js


if  (recargarPagina=="SI") {
	location.reload();
	}
if  (recargarPagina=="OFERTA") {
	window.location = "/miLaborum/index.html";
	}
}

imprimirAviso= function(nombre)
{

  var ficha = document.getElementById(nombre);
  var ventimp = window.open('imp.html ', 'popimpr');
  var htmlAviso =ficha.innerHTML; 
 
  htmlAviso=	"<style type='text/css'>h3 { background: #e1e2d8; border: none; padding-left: 5px; color: #000; } "+
  					" table { border: 1px solid #e1e2d8; margin: 0 0 10px 0 ; padding: 5px; " +
  					"font-size: 11px; font-family: Arial, Helvetica, sans-serif;}"+
  					" </style>"+
  					htmlAviso+"<script language='JavaScript' type='text/javascript'>"+
			  		" document.getElementById('accionesId2').style.visibility='hidden';"+
			  		" document.getElementById('accionesId1').style.visibility='hidden';"+
					"</script>";
			  	
			  	
  
  ventimp.document.write(htmlAviso);
  ventimp.document.close();
  ventimp.print();
  ventimp.close();
}


imprimirCvs = function(){
	//alert("imprimirCvs en functions.js");
	//alert(typeProductRankingId);
	var idSeleccionados=mostrarSeleccionLista();
	
	var codigoProceso=0;
	var estadoDeSeleccionCV=0;
	
	if (typeProductRankingId==1){
		codigoProceso=idAvisoSeleccionado;
		estadoDeSeleccionCV= estadoCv;
	}
	else if (typeProductRankingId==2){
		idAvisoSeleccionado=idReclutamiento;
		codigoProceso=idReclutamiento;
		estadoDeSeleccionCV = estado;
	}
	
 	if (idSeleccionados!="" || paramAll ==1){
 		var url = '/appjob/jobs';
		var pars = ""+
			"action=CvsHTML&listIdsUser="+idSeleccionados+
			"&idAvisoSeleccionado="+idAvisoSeleccionado+
			"&tipoProceso="+typeProductRankingId+
			"&paramAll="+paramAll+
			"&estadoCv="+estadoDeSeleccionCV+
			"&filtro="+obtenerValorFiltro()+
			"&masivo=1";
			//alert(pars);
			$('portada').startWaiting('bigWaiting');
        new Ajax.Request(
		url,
		{
			method:'POST',
			parameters: pars,
			encoding: characterEncoding,
			onSuccess: function(resp){
			//alert("hola");
								$('portada').stopWaiting();
								var dataContenido = resp.responseJSON || "no response text";
								
								//var ventimp = window.open('_blank', 'popimpr');
								var page_html=dataContenido.html+"<script type=\"text\/javascript\"> window.print(); document.getElementById('breaker_id').style.display='none';</script>";
								/*if (ventimp==null) ventimp=window.open('_blank', 'popimpr');
								ventimp.document.write(page_html);
								ventimp.document.close();
								 return false;*/
								 	winpop=window.open("","");
								 	if (winpop==null) winpop=window.open("","");
									winpop.focus();
									winpop.document.open();
									with (winpop)
									{
									winpop.document.write(page_html);
									}
									winpop.document.close();
									
							}
		}
  	    );

 	}

}

var _typeLightBox=2;

var getStatusCvAvisoPremium= function(estadoCv){
var estadoCv2=parseInt(estadoCv);
		 switch(estadoCv2){
		 case 1://disponible 
		 	return "DISPONIBLES"; 
		 case 2://seleccionado
		 	return "SELECCIONADOS";
		 case 3://eliminado
		 	return "ELIMINADOS";
		 }
	
}

var getStatusCvBodega= function(estadoCv){
	var estadoCv2=parseInt(estadoCv);
	switch(estadoCv2){
		 case 0://disponible 
		 	return "DISPONIBLES"; 
		 case 2://seleccionado
		 	return "SELECCIONADOS";
		 case 3://eliminado
		 	return "ELIMINADOS";
	}
	
}
encodeHTML = function (string) {
        return escape(this.utf8_encode(string));
    }
    
utf8_encode = function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    }


utf8_decode = function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }
        return string;
    }


var decodeHTML = function(html) {
	//alert(">>>>>:"+utf8_decode(unescape(html.replace(/\+/g, " "))));
	return utf8_decode(unescape(html.replace(/\+/g, " ")));
	
}
var switchLightBoxPercent= function(titulo,url,ancho,largo,cerrar){
	//var jkit = java.awt.Toolkit.getDefaultToolkit();
	//var scrsize = jkit.getScreenSize();
	tAnc = screen.width;
	tAlt = screen.height;
	//alert('w: '+tAnc+'-h:'+tAlt);
	ancho = ((tAnc*ancho)/100);
	largo = ((tAlt*largo)/100);
	switchLightBox(titulo,url, ancho, largo);
}

var switchLightBox= function(titulo,url,ancho,largo,cerrar){//considerar librerias
	
	titulo = '<br/>' + titulo;

	switch(_typeLightBox){
		case 1:
			Lightbox.showBoxByAJAX(url, ancho, largo); 
			break;
		case 2:
			if (cerrar==1) 
				Modalbox.show(url, {title: titulo, width: ancho, height: largo , closeValue:"" });
				
			else{
				 Modalbox.show(url, {title: titulo, width: ancho, height: largo }); 
			}
			
			
			break;
	}
} 

var switchLightBoxClose= function(){
	switch(_typeLightBox){
		case 1:
			Lightbox.hideBox();
			break;
		case 2:
			Modalbox.hide();
			break;
	}
}


var beginRequest=function (sender, args)
	{
		//alert("start");
		window.status = "Please wait...";
		document.body.style.cursor = "wait";
	}

var pageLoaded=	function (sender, args)
	{
		//alert("end");
		window.status = "Done";
		document.body.style.cursor = "default";
	}


var incrementaBarra=function(objetoImg, pixelsOrigen, pixelsDestino)
	{
		objetoImg.pixelsActuales = pixelsOrigen;
		objetoImg.style.backgroundPosition = objetoImg.pixelsActuales+'px';
		objetoImg.pixelsDestino = pixelsDestino;
		objetoImg.aumentador = function() {
			this.pixelsActuales += valorIncrementoBarra;
			this.style.backgroundPosition = this.pixelsActuales+'px';
			if (this.pixelsDestino<=this.pixelsActuales)
				clearInterval(this.tid);
		}
		objetoImg.tid = setInterval( function() { objetoImg.aumentador(); } ,  velocidadIncrementoBarra);
	}
var Text=function( strValue )
{
	return strValue.substring(strValue.indexOf('!') + 1, strValue.length)
}

 var Value=function( strValue )
{
	return strValue.substring(0, strValue.indexOf('!'))
}


 var  toggleDivDisplay=function( divName, imgName, plusPath, minusPath )
{
	var divElement = document.getElementById(divName);
	var imgElement = document[imgName];


	if (divElement.style.display == "block"){
		divElement.style.display="none";
		imgElement.src = plusPath;
	}else {
		divElement.style.display="block";
		imgElement.src = minusPath;
	}
}


 var  collapseSection=function( divName, imgName, plusPath )
{
	var divElement = document.getElementById(divName);
	var imgElement = document[imgName];

	divElement.style.display="none";
	imgElement.src = plusPath;
}

 var  expandSection=function( divName, imgName, minusPath )
{
	var divElement = document.getElementById(divName);
	var imgElement = document[imgName];

	divElement.style.display="block";
	imgElement.src = minusPath;
}




  var toggleElementDisplay =function(elementName, status)
{
	var objElement = document.getElementById(elementName);
	if(objElement!=null) objElement.style.display= status;
}


  var displayError =function(divId, Message)
{
	var divElement = document.getElementById(divId + "Error");
	var Element = document.getElementById(divId);
	divElement.innerHTML = Message
}

  var hideError=function(divId)
{
	var divElement = document.getElementById(divId + "Error");
	divElement.innerHTML = "&nbsp;"
}

  var elementStatusById =function(elementId)
{
	var objElement = document.getElementById(elementId);

	if (objElement.style.display == "none")
		return 'hidden';
	else
		return 'visible';
}


var ReadCookie = function(cookieName) {
	var theCookie=""+document.cookie;
	var ind=theCookie.indexOf(cookieName);
	if (ind==-1 || cookieName=="") return "";
	var ind1=theCookie.indexOf(';',ind);
	if (ind1==-1) ind1=theCookie.length;
	return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}


  var isodatetime = function() {
	var today = new Date();
	var year  = today.getYear();
	if (year < 2000) year = year + 1900;
	var month = today.getMonth() + 1;
	var day  = today.getDate();
	var hour = today.getHours();
	var hourUTC = today.getUTCHours();
	var diff = hour - hourUTC;
	var hourdifference = Math.abs(diff);
	var minute = today.getMinutes();
	var minuteUTC = today.getUTCMinutes();
	var minutedifference;
	var second = today.getSeconds();
	var timezone;
	if (minute != minuteUTC && minuteUTC < 30 && diff < 0) { hourdifference--; }
	if (minute != minuteUTC && minuteUTC > 30 && diff > 0) { hourdifference--; }
	if (minute != minuteUTC) {minutedifference = ":30";}else {minutedifference = ":00";}
	if (hourdifference < 10) {timezone = "0" + hourdifference + minutedifference;}else {timezone = "" + hourdifference + minutedifference;}
	if (diff < 0) {timezone = "-" + timezone;}
	else {timezone = "+" + timezone;}
	if (month <= 9) month = "0" + month;
	if (day <= 9) day = "0" + day;
	if (hour <= 9) hour = "0" + hour;
	if (minute <= 9) minute = "0" + minute;
	if (second <= 9) second = "0" + second;
	return year + "" + month + "" + day + ""+ hour + "" + minute;
}


  var getUserData =function(cookieName) {
	user = {userid:0, email:"", key:"", cvfUpdate:"",nombreUser:"",industria:"",tipoTrabajo:"",areaTrabajo:"",personalData:0,totalEstudios:0,totalExperciencia:0};
	var userData = ReadCookie(cookieName);
	var userData = userData.replace(/\"/g, "");
	if (userData != '') {
		var uData= userData.split(',');
		if(uData.length==11){
			var nomUser=decodeURI(escape(uData[4]));
			nomUser=nomUser.replace(/\+/g," ");
			user = {userid:uData[0], email:uData[1], key:uData[2], cvfUpdate:uData[3], nombreUser:nomUser, industria:uData[5], tipoTrabajo:uData[6], areaTrabajo:uData[7], personalData:uData[8], totalEstudios:uData[9], totalExperciencia:uData[10]};
		}
	}
	return user;
}
  var getUserLastData = function (cookieName) {		  
	var uld ="";	
	var userData = ReadCookie(cookieName);	
	userData = decodeHTML(userData);
	try{
		uld = userData.evalJSON(userData);
		if(typeof uld == "string"){
			uld = uld.evalJSON();
		}
	}catch(e){		
		uld = new Object();
		uld.email = userData;
	}
	
	return uld;
	
  }

var obtenerParametrosURL=function(){

		var parametrosURL= new Array();
		var myQueryString=document.location.search;
		
		if (myQueryString[0]='?')
		{
			myQueryString=myQueryString.substr(1, myQueryString.length-1);
		}
	
		if(myQueryString.length>0){
			var parts = myQueryString.split("&");
			for (var i=0;i<parts.length;++i){
	    		parametrosURL[i]= (parts[i].split("="))[1];
	    	}
		}
		return parametrosURL;
		
}

var obtenerQueryURL=function(){

		var myQueryString=document.location.search;
		if (myQueryString[0]='?')
		{
			myQueryString=myQueryString.substr(1, myQueryString.length-1);
			if(myQueryString.length>0){
				return myQueryString;
			}
		}
		return "";
		
}

var getUserDataEmpresa =function(cookieName) {
  	user = {userid:0,usuarioEmpresaId:"", email:"",key:"",nombreUser:"",keyEnt:"",tipUser:"",empresa:"",gTipEnt:"-1",gSucId:"-1",gEntPat:"-1",gPerFun:"",logo:"",logoInd:"",gContratad:"",stindusId:""};
	var userDataEmpresa = ReadCookie(cookieName);
	var userDataEmpresa = userDataEmpresa.replace(/\"/g, "");
	var userId = 0;
	var usuarioEmpresaId=0;
	var userEmail = "";
	var key = "";
	var nombreUser="";
	var keyEnt="";
	var tipUser="";
	var _gTipEnt = "-1";
	var _gSucId = "-1";
	var _gEntPat = "-1";
	var _gPerFun = "-1";
	var _logo = "";
	var _logoInd = "";
	var _gContratad= "0";
	var _stindusId= "0";
	
	if (userDataEmpresa != '') {
		var uData= userDataEmpresa.split(',');
		if(uData.length>=8){
			var nomUser=decodeURI(escape(uData[4]));
			var nomEmpresa=decodeURI(escape(uData[7]));
			nomUser=nomUser.replace(/\+/g," ");
			nomEmpresa=nomEmpresa.replace(/\+/g," ");
			// si se agregaron valiables de gestion <JV>
			if (uData.length>=11){
				_gTipEnt = uData[8];
				_gSucId  = uData[9];
				_gEntPat = uData[10];
				_logo     = uData[11];
				_logoInd  = uData[12];
			}
			if (uData.length>14){
				// sacar variables de Syncro
				_gPerFun = uData[13];
				_gContratad = uData[15];
				_stindusId = uData[16];
			}
			
			user = {userid:uData[0],usuarioEmpresaId:uData[1], email:uData[2], key:uData[3], nombreUser:nomUser,keyEnt:uData[5],tipUser:uData[6],empresa:nomEmpresa,gTipEnt:_gTipEnt,gSucId:_gSucId,gEntPat:_gEntPat,gPerFun:_gPerFun,logo:_logo,logoInd:_logoInd,gContratad:_gContratad,stindusId:_stindusId};
		}
		
	}
	return user;
}


  var validaRut =function( Objeto ){

      var tmpstr = "";
      var intlargo = Objeto

       if (intlargo.length> 0){
              crut = Objeto
               largo = crut.length;
          if ( largo <2 )
          {
              return false;
          }
          for ( i=0; i <crut.length ; i++ )
                      if ( crut.charAt(i) != ' ' && crut.charAt(i) != '.' && crut.charAt(i) != '-' )
                       {
                      tmpstr = tmpstr + crut.charAt(i);
                      }
                      
          rut = tmpstr;
          
          /********************************/
          /*Se elimina linea por los ceros*/
          /********************************/
          //if (parseInt(rut)*1==0) { return false;}
          
          crut=tmpstr;
          largo = crut.length;
          if ( largo> 2 )
              rut = crut.substring(0, largo - 1);
          else
              rut = crut.charAt(0);
          dv = crut.charAt(largo-1);
          if ( rut == null || dv == null )
                  return 0;
          var dvr = '0';
          suma = 0;
          mul  = 2;
          for (i= 1; i<= rut.length ; i++ )
          {
              suma = suma + rut.charAt(rut.length-i) * mul;
              if (mul == 7)
                  mul = 2;
              else
                  mul++;
          }
          res = suma % 11;
          if (res==1)
              dvr = 'k';
          else if (res==0)
              dvr = '0';
          else
          {
              dvi = 11-res;
              dvr = dvi + "";
          }
          if ( dvr != dv.toLowerCase() )
          {
          return false;
          }

          return true;
        }
      }
      
var checkMail = function(email){
	/*
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (filter.test(email)) return true;
	else return false;
	*/
	var arrayParamTokens = email.split(';')
	var estado=0;
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	for (var count = 0; count < arrayParamTokens.length; count++){
		var emailCheck =arrayParamTokens[count] ;
		if (emailCheck.length>0){
		   	if (filter.test(emailCheck)){
		   	 	estado =1;
		   	}else{
		   		estado=0;
		   	}
	    }
	}
	if (estado==1){
		return true;
	}else{
		return false;
	}	
}




 
var setCookie = function(name, value, expires, path, domain, secure)
{path="/"
  document.cookie =
    name+"="+value+
    (expires ? "; expires="+expires.toGMTString() : "")+
    (path    ? "; path="   +path   : "")+
    (domain  ? "; domain=" +domain : "")+
    (secure  ? "; secure" : "");
}      
  var setCookieLT = function(name, value, lifetime, path, domain, secure)
{ 
  if (lifetime)
    lifetime = new Date(Date.parse(new Date())+lifetime*120000);
  setCookie(name, value, lifetime, path, domain, secure);
}



var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
var chrsz   = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */

  var hex_md5=function(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}

  var core_md5 =function(x, len)
{
  x[len >> 5] |= 0x80 << ((len) % 32);
  x[(((len + 64) >>> 9) << 4) + 14] = len;

  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;

    a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
    d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
    c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
    b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
    a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
    d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
    c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
    b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
    a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
    d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
    c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
    b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
    a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
    d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
    c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
    b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);

    a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
    d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
    c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
    b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
    a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
    d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
    c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
    b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
    a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
    d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
    c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
    b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
    a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
    d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
    c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
    b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);

    a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
    d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
    c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
    b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
    a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
    d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
    c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
    b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
    a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
    d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
    c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
    b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
    a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
    d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
    c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
    b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);

    a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
    d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
    c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
    b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
    a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
    d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
    c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
    b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
    a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
    d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
    c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
    b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
    a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
    d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
    c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
    b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
  }
  return Array(a, b, c, d);

}

  var md5_cmn=function(q, a, b, x, s, t)
{
  return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
  var md5_ff=function(a, b, c, d, x, s, t)
{
  return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
  var md5_gg=function(a, b, c, d, x, s, t)
{
  return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
  var md5_hh=function(a, b, c, d, x, s, t)
{
  return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
  var md5_ii=function(a, b, c, d, x, s, t)
{
  return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}

  var safe_add=function(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

  var bit_rol=function(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}

  var str2binl=function(str)
{
  var bin = Array();
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < str.length * chrsz; i += chrsz)
    bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
  return bin;
}

  var binl2hex=function(binarray)
{
  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i++)
  {
    str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
           hex_tab.charAt((binarray[i>>2] >> ((i%4)*8  )) & 0xF);
  }
  return str;
}





var insertaNuevoCombo = function(param,divIdNuevoSelect,htmlOptionsSelect,selectId,onChange)
	{
			var element = document.getElementById(divIdNuevoSelect);
	      	while (element.firstChild) element.removeChild(element.firstChild);
	
			new Ajax.Request
			("/cv/ajax.data/"+htmlOptionsSelect+"/"+param+".html",
				{
				method:'POST',encoding: characterEncoding,asynchronous:false,
				onSuccess : function(resp) {
											var textReturn = resp.responseText || "no response text";
											document.getElementById(divIdNuevoSelect).innerHTML="<select class='insel' name="+selectId+" id="+selectId+" onChange="+onChange+">"+textReturn+"</select><br /><span class='errorText' id='"+selectId+"Error'></span>";
											}
	
				}
			);
			
			}
var insertaNuevoComboEmpresa = function(param,divIdNuevoSelect,htmlOptionsSelect,selectId,onChange)
	{
			var element = document.getElementById(divIdNuevoSelect);
	      	while (element.firstChild) element.removeChild(element.firstChild);
	
			new Ajax.Request
			("/empleadores/ajax.data/"+htmlOptionsSelect+"/"+param+".html",
				{
				method:'POST',encoding: characterEncoding,asynchronous:false,
				onSuccess : function(resp) {
											var textReturn = resp.responseText || "no response text";
											document.getElementById(divIdNuevoSelect).innerHTML="<select class='insel' name="+selectId+" id="+selectId+" onChange="+onChange+">"+textReturn+"</select><br /><span class='errorText' id='"+selectId+"Error'></span>";
											}
	
				}
			);
		
	}
var obtenerIdRadioSeleccionado=function(radioId){
	var largo=radioId.length;
	
    if (largo==undefined) largo=1;
    if (largo==1)   {
    	if (radioId.checked)
    		return radioId.value;
    	}
    	else{
			for (var i=0; i<largo; i++) {
				if (radioId[i].checked) return radioId[i].value;
				}
			}
	return 0;
}
getCurrentRadio=function(idElemento){

	var elemento= document.getElementById(idElemento);
	for (var i=0;i<elemento.elements.length;i++)
	{
		var e=elemento.elements[i];
		if ((e.type=='radio') && (e.checked==true))
		{
			return e.value;
		}
	}
	return 0;
}

var obtenerListaRadios=function(idElemento){
	var ids=new Array();
	var elemento= document.getElementById(idElemento);
	for (var i=0;i<elemento.elements.length;i++)
	{
		var e=elemento.elements[i];
		if ((e.name != 'checkTodos') && (e.type=='radio') && (e.checked==true))
		{
			ids.push(e.value);
		}
	}
	return ids;
}

var obtenerListaChecked=function(idElemento){
	var ids=new Array();
	var elemento= document.getElementById(idElemento);
	for (var i=0;i<elemento.elements.length;i++)
	{
		var e=elemento.elements[i];
		if ((e.name != 'checkTodos') && (e.type=='checkbox') && (e.checked==true))
		{
			ids.push(e.value);
		}	
	}
	return ids;
}

var obtenerProactivos=function(idElemento){
	var proCont	= 0;
	var ids=new Array();
	var elemento= document.getElementById(idElemento);
	for (var i=0;i<elemento.elements.length;i++)
	{
		var e=elemento.elements[i];
		if ((e.name != 'checkTodos') && (e.type=='checkbox') && (e.checked==true))
		{
			if(document.getElementById(+e.value+'proactivo').firstChild.nodeValue==1) proCont ++;
		}	
	}
	return proCont;
}

var obtenerTotPostulantes=function(idElemento){
	var totPos	= 0;
	var ids=new Array();
	var elemento= document.getElementById(idElemento);
	for (var i=0;i<elemento.elements.length;i++)
	{
		var e=elemento.elements[i];
		if ((e.name != 'checkTodos') && (e.type=='checkbox') && (e.checked==true)) totPos++;
	}
	return totPos;
}



/************************SELECCCIONADOR MULTIPLE JV *************************************/
var obtenerValorFiltro = function (){
	var ParamFiltro;
	try {
		ParamFiltro = filtroGlobal;				
	}catch(mierror){
		ParamFiltro=0;
	} 
	return ParamFiltro;
}

var eliminarUsuarioArray = function (user,array){
	salir = 0;
	var i;
	if (array == 'seleccionados'){
		
		for ( i=0;i<usersSeleccionados.length && salir==0;i++){
			if (usersSeleccionados[i]==user){
				usersSeleccionados.splice(i,1);
				salir = 1;
			}
		}	
	}
	else{
		for ( i=0;i<usersDesSeleccionados.length && salir==0;i++){
			if (usersDesSeleccionados[i]==user){
				usersDesSeleccionados.splice(i,1);
				salir = 1;
			}
		}	
	}
}

var buscaSeleccionados = function (user){

	var i;
	for ( i=0;i<usersSeleccionados.length ;i++){
		if (usersSeleccionados[i]==user)
			return true	
	}
	return false;
}

var buscaDesSeleccionados = function (user){

	var i;
	for ( i=0;i<usersDesSeleccionados.length ;i++){
		if (usersDesSeleccionados[i]==user)
			return true	
	}
	return false;
}


function actualizaSeleccionados(user,estado,mostrarValor){
	
	if (estado){
		if(!buscaSeleccionados(user))
			usersSeleccionados[usersSeleccionados.length] = user;// Cuando el usuario esta no hay que repetirlo
		// eliminar de los desseleccionados
		eliminarUsuarioArray(user,'desSeleccionados');
	}
	else{
		// agregar a los desseleccionados
		if(!buscaDesSeleccionados(user))
			usersDesSeleccionados[usersDesSeleccionados.length] = user;
		// eliminar de los desseleccionados
		eliminarUsuarioArray(user,'seleccionados');
	}
	if (mostrarValor)
		actulizaCantidadSeleccionados();
	//$('cantCheck').innerHTML = $('cantCheck').value +aumento;
//alert("seleccionados desde ActualizaSeleccionados:"+usersSeleccionados);
	}

// actualiza la los numeros de cvs seleccionados y bloquea y desbloquea el mensaje
function actulizaCantidadSeleccionados(){
	var cantidad =0;
	if(paramAll ==1)
		cantidad = $('totalRegistros1').innerHTML - usersDesSeleccionados.length;
	else
		cantidad = usersSeleccionados.length;

	$('cantCheck').innerHTML = cantidad;
	if (cantidad >0 || paramAll==1)
		$('MsgExport').style.display = 'block';
	else 
		$('MsgExport').style.display = 'none';
	
}

var mostrarSeleccionLista=function(){
	
	var ids="";
	// si se seleccionaron todos, se debe ver si alguno se ha desseleccionado, en caso contrario contar solo los seleccioandos
	if (paramAll == 1){
		for (var i=0;i<usersDesSeleccionados.length;i++)
			ids+= usersDesSeleccionados[i]+",";
			try{actulizaCantidadSeleccionados();}
			catch(err){};
		if (i>0)
			ids = "DES,"+ids;
	}
	else{
		for (var i=0;i<usersSeleccionados.length;i++)
			ids+= usersSeleccionados[i]+",";
		try{actulizaCantidadSeleccionados();}
		catch(err){};

		if (i>0)
			ids = "SEL,"+ids;
	}
	ids = ids.substring(0, ids.length-1);
	return ids;
}


checkAll = function(formAll){
	
	jc=1;
	impar = 1;
	var formulario=$(formAll);
	var e="";
		for (var i=0;i<formulario.elements.length;i++){
			e=formulario.elements[i];
			if ((e.name != 'checkTodos') && (e.type=='checkbox')){
				if (formulario.checkTodos.checked){
					$(e.value).className="bordePunteado impar2";
					$(e.value+"_2").className="bordePunteado impar2";
				}
				else if (impar==0){
					$(e.value).className="bordePunteado impar";
					$(e.value+"_2").className="bordePunteado impar";
					impar =1;
				}
				else{
					$(e.value).className="bordePunteado par";
					$(e.value+"_2").className="bordePunteado par";
					impar =0;
				}
				e.checked=formulario.checkTodos.checked;
				$('cantCheck').innerHTML=jc;
				jc++
				actualizaSeleccionados(e.value,formulario.checkTodos.checked,false);
			}
		}
		actulizaCantidadSeleccionados();
		
	}

allCheck = function(v){
	var estado = $('checkTodos').checked;
	if (v==0){
		paramAll =0;
		$('checkTodos').checked = false;
		checkAll('FormCvs');
	}
	else{
		paramAll=1;
		$('checkTodos').checked = true;
		checkAll('FormCvs');
		$('checkTodos').checked = estado;
	}
	
	reiniciaArreglosSeleccion();
	
}

reiniciaArreglosSeleccion = function (){
	usersDesSeleccionados.splice(0,usersDesSeleccionados.length);	
	usersSeleccionados.splice(0,usersSeleccionados.length);
	actulizaCantidadSeleccionados();
}
/*****************************************************************************************/
var obtenerListaCheckeds=function(checkboxId){
	var CvsChecked=new Array();
	var largo=checkboxId.length;
    if (largo==undefined) largo=1;
    
    if (largo==1)   {
    	if (checkboxId.checked)
    		CvsChecked.push(checkboxId.value);
    	}
    	else{
    	
			for (var i=0; i<largo; i++) {
			
				if (checkboxId[i].checked) 
						CvsChecked.push(checkboxId[i].value);
				    			     }
		}
		return CvsChecked;
}


var clearElement=function(idElement)
{
      var element = document.getElementById(idElement);
      while (element.firstChild) {
      element.removeChild(element.firstChild);
      }
}


function $RF(el, radioGroup)
{
var el = document.getElementById(el);
//if(el==null) return null;
	if($(el).type && $(el).type.toLowerCase() == 'radio')
	{
		var radioGroup = $(el).name;
		var el = $(el).form;
	} else if ($(el).tagName.toLowerCase() != 'form') {
		return false;
	}
	var checked = $(el).getInputs('radio', radioGroup).find(
		function(re) {return re.checked;}
	);
	return (checked) ? $F(checked) : null;
}
	
fMostrarOcultar=function(name,value){
	div  = document.getElementById(name);
	valor = div.style.display;
	if(valor=='block'){
		div.style.display='none';
	}else if(div.style.display=='none'){
		div.style.display='block';
	}
}



function addOptionInSelect(selectbox, value, text)
{
	var testSelect = $(selectbox);
	var option = document.createElement("OPTION") ;
	option.value=value;
	option.text=text;
	//testSelect.setAttribute("onChange","alert('hola');");
	testSelect.options.add(option);
	
}

function addOptionSelect(selectbox, value, text)
{
	var testSelect = $(selectbox);
	var option = new Option(text,value);
	testSelect.options.add(option);
}

function appendOptionLast(selectbox, value, text)
{
  var elOptNew = document.createElement('option');
  elOptNew.text =  text;
  elOptNew.value = value;
  var elSel = document.getElementById(selectbox);

  try {
    elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
  }
  catch(ex) {
    elSel.add(elOptNew); // IE only
  }
}


function clearOptionInSelect(selectbox)
{
	var testSelect = $(selectbox);
	if (testSelect==undefined) return;
	while(testSelect.firstChild)
	{
	    testSelect.removeChild(testSelect.firstChild)
	}
}


function removeOptionInSelect(selectboxId)
{

	var selectbox = document.getElementById(selectboxId);
		var i;
		for(i=selectbox.length-1;i>=0;i--)
		{
			if(selectbox.options[i].selected){
			selectbox.remove(i);
			}
		}
}



function removeOptionSelected(selectboxId)
{
  var elSel = document.getElementById(selectboxId);
  var option;
  var i;
  for (i = elSel.length - 1; i>=0; i--) {
    if (elSel.options[i].selected) {
      //  text=elSel.options[i].text;
      //  val=elSel.options[i].value;
      //  alert(text+","+val+":i:"+i);
      option=elSel.options[i];
      elSel.remove(i);
      //  alert(text+","+val+":i:"+i);
      return option;
      
    }
  }
}

	
function addRemoveItems(element)
{
   var i,j,r;
   if(element.id == "add")
   {
      var listSource = document.getElementById("listaA");
      var listTarget = document.getElementById("listaB");
      var optionsSource = listSource.getElementsByTagName("option");
   }
   else
   {
      var listSource = document.getElementById("listaB");
      var listTarget = document.getElementById("listaA");
      var optionsSource = listSource.getElementsByTagName("option");
   }
   for(i=0;i<optionsSource.length;i++){
         opt=new Option(optionsSource[i].text,optionsSource[i].value);
         eval(listTarget.options[optionsSource[i].value-1]=opt);
   }
   var r=0;
   while(r<optionsSource.length){
         listSource.remove(r);
   }
} 



function isValidEmail(email, required) {

email=email.trim();

    if (required==undefined) {   // if not specified, assume it's required
        required=true;
    }
    if (email==null) {
        if (required) {
            return false;
        }
        return true;
    }
   
    if (email.length==0) {  
        if (required) {
            return false;
        }
        return true;
    }
    
    if (! allValidChars(email)) {  
        return false;
    }
    
    if (email.indexOf("@") < 1) { 
       return false;
    } 
     
    if (email.lastIndexOf(".") <= email.indexOf("@")) {  
        return false;
    } 
    
    if (email.indexOf("@") == email.length) {  
       return false;
    } 
     
    if (email.indexOf("..") >=0) { 
	return false;
    } 
    
    if (email.indexOf(".") == email.length) {  
	return false;
    }
    
    return true;
}

function allValidChars(email) {
  var parsed = true;
  var validchars = "abcdefghijklmnopqrstuvwxyz0123456789@.-_";
  for (var i=0; i < email.length; i++) {
    var letter = email.charAt(i).toLowerCase();
    if (validchars.indexOf(letter) != -1)
      continue;
    parsed = false;
    break;
  }
  return parsed;
}


divOcultarMostrar=function(name,value){
	div  = document.getElementById(name);
	if (value==undefined) {  
		value='none';
	}
	if(value=='block'){
		div.style.display='block';
	}else if(value=='none'){
		div.style.display='none';
	}
}
	
	
	
	
/* **** */	
var setListaOptionAnnosPasadoInitNOWDESC =function(cantidad,selectName,defecto) {
	var time = new Date();
	var year = time.getYear();
	if (year < 1900) year = year + 1900;
	var date = year;
	var sentido = -1;
	addOptionInSelect(selectName, '0',defecto);
	for(i=0;i<cantidad;i++){
		addOptionInSelect(selectName, date, date);
		date=date+(sentido);
	}	
}


var setListaOptionAnnosPasadoInitNOWASC =function(cantidad,selectName,defecto) {
	var time = new Date();
	var year = time.getYear();
	if (year < 1900) year = year + 1900;
	var date = year-cantidad;
	var sentido = 1;
	addOptionInSelect(selectName, '0',defecto);
	for(i=0;i<cantidad;i++){
		date=date+(sentido);
		addOptionInSelect(selectName, date, date);
	}	
}
var setListaOptionAnnosPasadoNOWASC =function(cantidad,selectName) {
	var time = new Date();
	var year = time.getYear();
	if (year < 1900) year = year + 1900;
	var date = year-cantidad;
	var sentido = 1;
	for(i=0;i<cantidad;i++){
		date=date+(sentido);
		addOptionInSelect(selectName, date, date);
	}	
}


var setListaOptionAnnosPasadoNOWDESC =function(cantidad,selectName) {
	var time = new Date();
	var year = time.getYear();
	if (year < 1900) year = year + 1900;
	var date = year;
	var sentido = -1;
	for(i=0;i<cantidad;i++){
		addOptionInSelect(selectName, date, date);
		date=date+(sentido);
	}	
}



var setListaOptionAnnosPasadoAnnoASC =function(anoInicial,selectName) {
	var time = new Date();
	var year = time.getFullYear();
	for(i=anoInicial;i<year+1;i++){
		addOptionInSelect(selectName, i, i);
	}	
}



var setListaOptionAnnosPasadoAnnoDESC =function(anoInicial,selectName) {
	var time = new Date();
	var year = time.getFullYear();
	for(i=year;i+1>anoInicial;i--){
		addOptionInSelect(selectName, i, i);
	}	
}	

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/g,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/g,"");
}


var isEmpty =function(v) {
	return  ((v == null) || (v.length == 0)); // || /^\s+$/.test(v));
}


var validateDateFull =function(d,m,a) {
	if (isNaN(a) || a.length<4 || parseFloat(a)<1900){  
		return -3;  
	}  
	if (isNaN(m) || parseFloat(m)<1 || parseFloat(m)>12){  
		return -2;
	}
	if (isNaN(d) || parseInt(d, 10)<1 || parseInt(d, 10)>31){  
		return -1;
	}
	
	if (m==4 || m==6 || m==9 || m==11 || m==2) {  
		if (m==2 && d > 28 || d>30) {  
			return -1;  
		}  
	} 	
	var fecha = m+"/"+d+"/"+a;
	var test = new Date(fecha);
	
	if(!(isEmpty(test) || !isNaN(test))){
		return 0;
	}
	return 1;
	
	
	
	
	//return isEmpty(inputDate) || !isNaN(test);
}

var validateDate =function(inputDate) {
	var test = new Date(inputDate);
	return isEmpty(inputDate) || !isNaN(test);
}


function agregarAfavoritos() {
    if (window.sidebar&&window.sidebar.addPanel)
	    window.sidebar.addPanel("Laborum.com","http://www.laborum.com","");
    else
	    window.external.AddFavorite("http://www.laborum.com","Laborum.com")
}

randomAB = function(inferior,superior){
	var  numero = 0;
	if (inferior==undefined || superior ==undefined) return numero;
	try {

		numPosibilidades = superior - inferior;
		if (numPosibilidades<0) return numero;
		aleat = Math.random() * numPosibilidades;
		aleat = Math.round(aleat);
		var numero = parseInt(inferior) + aleat;
		if(numero > superior) numero = superior;
	}catch(ex) {  }	
	return numero;
}

clearElement = function(divName){
	var element = $(divName);
	while (element.firstChild) {element.removeChild(element.firstChild);}
}
function estaNumero(indice,numero){
	for(i=0;i<indice.length;i++){
		if(indice[i]==numero) return 1;
	}
	return 0;
}


function validaOferta(resp)
{
	var data = resp.responseJSON || "no response text";
	if (data.bError == 1) {
		alert("Usuario no Registrado");
	}else{
		if (data.bError == 0){
			alert("Aviso guardado");
			return false;
	}
	}
}

guardarOfertas = function(id) {
	if(userData.userid==0){
		//		Lightbox.showBoxByAJAX('/lightbox/usuarioNoRegistrado.html', 300, 200);
		lbMensajeAlerta("Usuario no registrado<br><br>Para guardar este aviso necesitas estar registrado") 
		return false;
	}else{
		var url = '/appjob/jobs';
		var pars = "action=GuardarAvisos&idAvisos="+id;
		new Ajax.Request(
		url,
		{
			method:'POST',
			parameters: pars,
			encoding: characterEncoding,
			onSuccess : validaOferta
		}
		);
	}		
}


var userData = getUserData("LABORUMPOSTULANTE");
var userLastData = getUserLastData("LABORUMPOSTULANTE_LASTDATA");
var porcGeneral=0;
var userDataEmpresa = getUserDataEmpresa("LABORUMEMPRESA");


/***************** paginacion indice contenidos ******************/
var registros;
var paginaActiva=1;
var idListaRegistros;
var indiceContenidoTop;
var indiceContenidoDown;
var totalPagRegistro;
var registroPorPag;
var totalRegistros;
var rangoMaximoIndice;
var codigoContentHTML;   //set para cada template que codifique un contenido ver getHTML_Indice()



initIndiceContenido = function(topID,contenidoID,downID,regPorPag,rangoMaxIndice,contenido){


paginaActiva=1;
clearElement(topID);
clearElement(contenidoID);
clearElement(downID);

	registros = contenido;
	idListaRegistros=contenidoID;
	indiceContenidoTop=topID;
	indiceContenidoDown=downID;
	registroPorPag=regPorPag;
	rangoMaximoIndice=rangoMaxIndice;
	setParametrosContenido();
	generaContenido('1');
}


setParametrosContenido= function(){
	var resttotalPagRegistro;
	totalRegistros=parseInt(registros.length);
	totalPagRegistro = Math.floor(eval(totalRegistros / parseInt(registroPorPag)));
	resttotalPagRegistro = eval(totalRegistros % parseInt(registroPorPag));
	if (resttotalPagRegistro>0) totalPagRegistro=totalPagRegistro+1;
	
}

changeindexResultAvisos= function(indexPage){


	var index=0;
	var indexBefore=1;
	var indexAfter=0;
	var margen=1;
	var HTML_linkPrimero=getHTML_Indice("","",4);
	var HTML_linkUltimo=getHTML_Indice("","",5);
     
	clearElement(indiceContenidoTop);
	clearElement(indiceContenidoDown);
	var firstPivot=indexPage-(Math.floor(eval(rangoMaximoIndice/2)));
	if (firstPivot<=0) firstPivot=1;
	var endPivot=firstPivot+rangoMaximoIndice;

	if (paginaActiva>1) indexBefore=parseInt(paginaActiva) - margen;
	indexAfter=parseInt(paginaActiva)+margen;

	var paginaSiguiente = parseInt(paginaActiva)+1;
	var paginaAnterior = parseInt(paginaActiva)-1;

	if (indexPage==firstPivot)
	{
		
		new Insertion.Bottom(indiceContenidoTop,HTML_linkPrimero);
		new Insertion.Bottom(indiceContenidoDown,HTML_linkPrimero);
	}else if(paginaActiva> firstPivot && paginaActiva< endPivot){
		new Insertion.Bottom(indiceContenidoTop,getHTML_Indice(paginaActiva,"",1));
		new Insertion.Bottom(indiceContenidoDown,getHTML_Indice(paginaActiva,"",1));
	}

	for (var i=firstPivot; i < endPivot; i++) {

	    	if (i<=totalPagRegistro){
	    		if (i==paginaActiva) {
	    				new Insertion.Bottom(indiceContenidoTop,getHTML_Indice(i,"",2));
	    				new Insertion.Bottom(indiceContenidoDown,getHTML_Indice(i,"",2));
	    			}else{
	    				new Insertion.Bottom(indiceContenidoTop,getHTML_Indice(i,"",6));
	    				new Insertion.Bottom(indiceContenidoDown,getHTML_Indice(i,"",6));
	    			}
	    		}
	   }

	if (paginaActiva==totalPagRegistro){

		new Insertion.Bottom(indiceContenidoTop,HTML_linkUltimo);
		new Insertion.Bottom(indiceContenidoDown,HTML_linkUltimo);
	}else if(paginaSiguiente >= firstPivot && paginaSiguiente < endPivot){
		new Insertion.Bottom(indiceContenidoTop,getHTML_Indice(paginaSiguiente,totalPagRegistro,3));
		new Insertion.Bottom(indiceContenidoDown,getHTML_Indice(paginaSiguiente,totalPagRegistro,3) );
	}
}

generaContenido= function(indexPage){


		var numPage=indexPage; var dato;var datoRegistro;
		var firstJobPage=(numPage-1)*registroPorPag;
		var lastJobPage=(numPage*registroPorPag);
		if (lastJobPage>totalRegistros) lastJobPage=totalRegistros;
		
			
		if (firstJobPage<totalRegistros ) {
				paginaActiva=indexPage;
				changeindexResultAvisos(indexPage);

				clearElement(idListaRegistros);

				if(firstJobPage<=totalRegistros)
				{
					for (i=firstJobPage; i < lastJobPage; i++) {
						datoRegistro = registros[i];
						var htmlResultado = getHTML_Contenido(datoRegistro,codigoContentHTML);
						new Insertion.Bottom(idListaRegistros,htmlResultado);
					}
				}
		}
		//else alert("Fin de paginas");

}

getHTML_Contenido = function(data,parameter){

	var logoReal = data.logo;

	if(logoReal.length==0) logoReal = "http://resource.laborum.cl/css/i/icons-industrias/"+data.logoIndustria;
	else logoReal="http://static.laborum.cl/"+logoReal;
	var HTML_Contenido_busquedaPorEmpresa="<div id='emp' class='oferta'><img src=\""+logoReal+"\"/><h3><a href='#' onClick=\"getOfertasEmpresa('"+data.codeJson+"');return false;\">"+data.empresa+"</a></h3><br></div>";
    	
	switch(parameter){
	 case 1: 	return HTML_Contenido_busquedaPorEmpresa;   break;
	 

	}
}


getHTML_Indice=function(val1,val2,parameter){

var HTML_linkPrimero="<a href=\"javascript:;\" class=\"AnteriorFondo\"> &laquo; Anterior </a>";
var HTML_linkUltimo="<a class=\"SiguienteFondo\" href=\"javascript:;\"> Siguiente &raquo;</a>";
var HTML_linkAnterior="<a  class=\"AnteriorFondo\" href=\"javascript:;\" onClick=\"generaContenido('"+ (val1-1) +"')\">&laquo; Anterior</a>";
var HTML_Indice="<b>"+ val1 +"</b>";
var HTML_IndiceActual="<a href=\"javascript:;\" onClick=\"generaContenido("+ val1 +")\"> "+ val1 +" </a>";
var HTML_linkSiguiente="<a class=\"SiguienteFondo\" href=\"javascript:;\" onClick=\"generaContenido("+ val1 +")\"> Siguiente &raquo;</a>";


    	
	switch(parameter){
	 case 1: 	return HTML_linkAnterior; 	break;
	 case 2: 	return HTML_Indice; 	 	break;
	 case 3: 	return HTML_linkSiguiente;  break; 
	 case 4:  	return HTML_linkPrimero; 	break;
	 case 5: 	return HTML_linkUltimo; 	break;
	 case 6: 	return HTML_IndiceActual;   break;
	 

	}
}	



/***************** FIN paginacion indice contenidos ******************/
/***************** PAGINACION POR DEMANDA ******************/

var paginaActivaDE=1;
var idListaRegistrosDE;
var indiceContenidoTopDE;
var indiceContenidoDownDE;
var totalPagRegistroDE;
var registroPorPagDE;
var totalRegistrosDE;
var rangoMaximoIndiceDE;
var codigoContentHTMLDE;
var totalDatos;
var registrosDE;



setParametrosContenidoDE= function(){
	var resttotalPagRegistroDE;
	totalRegistrosDE=totalDatos;
	totalPagRegistroDE = Math.floor(eval(totalRegistrosDE / parseInt(registroPorPagDE)));
	resttotalPagRegistroDE = eval(totalRegistrosDE % parseInt(registroPorPagDE));
	if (resttotalPagRegistroDE>0) totalPagRegistroDE=totalPagRegistroDE+1;
	
}

initIndiceContenidoDE = function(topID,contenidoID,downID,regPorPag,rangoMaxIndice,totalRegistrosDERetornados){


	paginaActivaDE=1;
	clearElement(topID);
	clearElement(contenidoID);
	clearElement(downID);
	
	totalDatos=totalRegistrosDERetornados;
	
	idListaRegistrosDE=contenidoID;
	indiceContenidoTopDE=topID;
	indiceContenidoDownDE=downID;
	registroPorPagDE=regPorPag;
	rangoMaximoIndiceDE=rangoMaxIndice;
	setParametrosContenidoDE();
	generaContenidoDE('1');
}

changeindexResultDE= function(indexPage){


	var index=0;
	var indexBefore=1;
	var indexAfter=0;
	var margen=1;
	var HTML_linkPrimero=getHTML_IndiceDE("","",4);
	var HTML_linkUltimo=getHTML_IndiceDE("","",5);
     
	clearElement(indiceContenidoTopDE);
	clearElement(indiceContenidoDownDE);
	var firstPivot=indexPage-(Math.floor(eval(rangoMaximoIndiceDE/2)));
	if (firstPivot<=0) firstPivot=1;
	var endPivot=firstPivot+rangoMaximoIndiceDE;

	if (paginaActivaDE>1) indexBefore=parseInt(paginaActivaDE) - margen;
	indexAfter=parseInt(paginaActivaDE)+margen;

	var paginaSiguiente = parseInt(paginaActivaDE)+1;
	var paginaAnterior = parseInt(paginaActivaDE)-1;

	if (indexPage==firstPivot)
	{
		new Insertion.Bottom(indiceContenidoTopDE,HTML_linkPrimero);
		new Insertion.Bottom(indiceContenidoDownDE,HTML_linkPrimero);
	}else if(paginaActivaDE> firstPivot && paginaActivaDE< endPivot){
		new Insertion.Bottom(indiceContenidoTopDE,getHTML_IndiceDE(paginaActivaDE,"",1));
		new Insertion.Bottom(indiceContenidoDownDE,getHTML_IndiceDE(paginaActivaDE,"",1));
	}

	for (var i=firstPivot; i < endPivot; i++) {

	    	if (i<=totalPagRegistroDE){
	    		if (i==paginaActivaDE) {
	    				new Insertion.Bottom(indiceContenidoTopDE,getHTML_IndiceDE(i,"",2));
	    				new Insertion.Bottom(indiceContenidoDownDE,getHTML_IndiceDE(i,"",2));
	    			}else{
	    				new Insertion.Bottom(indiceContenidoTopDE,getHTML_IndiceDE(i,"",6));
	    				new Insertion.Bottom(indiceContenidoDownDE,getHTML_IndiceDE(i,"",6));
	    			}
	    		}
	   }
	if (paginaActivaDE==totalPagRegistroDE){
		new Insertion.Bottom(indiceContenidoTopDE,HTML_linkUltimo);
		new Insertion.Bottom(indiceContenidoDownDE,HTML_linkUltimo);
	}else if(paginaSiguiente >= firstPivot && paginaSiguiente < endPivot){
		new Insertion.Bottom(indiceContenidoTopDE,getHTML_IndiceDE(paginaSiguiente,totalPagRegistroDE,3));
		new Insertion.Bottom(indiceContenidoDownDE,getHTML_IndiceDE(paginaSiguiente,totalPagRegistroDE,3) );
	}
}

generaContenidoDE= function(indexPage){

		
		var numPage=indexPage; var dato;var datoRegistro;
		var firstJobPage=(numPage-1)*registroPorPagDE;
		var lastJobPage=(numPage*registroPorPagDE);
		if (lastJobPage>totalRegistrosDE) lastJobPage=totalRegistrosDE;
				
		if (firstJobPage<totalRegistrosDE ) {
				paginaActivaDE=indexPage;
				
				changeindexResultDE(indexPage);//genera  paginador < 1 2 3 4 ...(indexPage)... n >

				clearElement(idListaRegistrosDE);
				
				//getRangoResultados(firstJobPage,lastJobPage);
				
				
		}
		else 
			alert("No hay resultados que desplegar");

}

getHTML_ContenidoDE = function(data,parameter){

	var HTML_Contenido_busquedaPorEmpresa="<div id='emp' class='oferta'><img src=\"http://static.laborum.cl/"+data.logo+"\"/><h3><a href='#' onClick=\"getOfertasEmpresa('"+data.codeJson+"');return false;\">"+data.empresa+"</a></h3><br></div>";
	var HTML_datos_cv_busqueda="<li>"+data.nombre+"</li>"
    	
	switch(parameter){
	 case 1: 	return HTML_Contenido_busquedaPorEmpresa;   break;
	 case 2:    return HTML_datos_cv_busqueda; break;
	 

	}
}


getHTML_IndiceDE=function(val1,val2,parameter){
//alert("${siteResource}/empleadores/css/i/flecha_izquierda.jpg");
//${siteResource}/empleadores/css/i/botones/
var HTML_linkPrimero="<p> Anterior </p> ";
var HTML_linkUltimo=" <p> Siguiente </p>";
var HTML_linkAnterior="<a><img src=\"http://resource.laborum.cl/empleadores/css/i/flecha_izquierda.jpg\" style=\"cursor:pointer;\" onClick=\"generaContenidoDE('1')\"/></a><a href=\"javascript:;\"  class=\"Anterior\" onClick=\"generaContenidoDE('"+ (val1-1) +"')\"> Anterior </a>";
var HTML_Indice="<b> "+ val1 +" </b>";
var HTML_IndiceActual="<a href=\"javascript:;\" onClick=\"buscarPostulante("+ val1 +")\"> "+ val1 +" </a>";
var HTML_linkSiguiente="<a href=\"javascript:;\"    class=\"Siguiente\"  onClick=\"buscarPostulante("+ val1 +")\"> Siguiente </a><a><img src=\"http://resource.laborum.cl/empleadores/css/i/flecha_derecha.jpg\" style=\"cursor:pointer;\"   onClick=\"buscarPostulante('"+val2+"')\"/></a>";

    	
	switch(parameter){
	 case 1: 	return HTML_linkAnterior; 	break;
	 case 2: 	return HTML_Indice; 	 	break;
	 case 3: 	return HTML_linkSiguiente;  break; 
	 case 4:  	return HTML_linkPrimero; 	break;
	 case 5: 	return HTML_linkUltimo; 	break;
	 case 6: 	return HTML_IndiceActual;   break;
	 

	}
}		


/***********************************************************************/


function formatNumber(num,prefix){
prefix = prefix || '';
num += '';
var splitStr = num.split('.');
var splitLeft = splitStr[0];
var splitRight = splitStr.length > 1 ? '.' + splitStr[1] : '';
var regx = /(\d+)(\d{3})/;
while (regx.test(splitLeft)) {
splitLeft = splitLeft.replace(regx, '$1' + '.' + '$2');
}
return prefix + splitLeft + splitRight;
}

function calcular_edad(yr, mon, day){
	TheDate = new Date();                     
	Month = TheDate.getMonth();              
	Day = TheDate.getDate();                 
	Year = TheDate.getYear();
	if (Year< 1000)
		Year+=1900
	Hour = TheDate.getHours();
	Minute = TheDate.getMinutes();
	Second = TheDate.getSeconds();   
	by = yr;
	bm = mon;
	bd = day;
	bh = 0;
	bmn =0;
	bs =0;
	BDate = Date.UTC(by,bm,bd,bh,bmn,bs);
	if (Year<2000) {              
		CDate = Date.UTC(Year,Month,Day,Hour,Minute,Second);
	} else {
		CDate = Date.UTC(Year,Month,Day,Hour,Minute,Second);
	}
	Age = CDate-BDate + (1000*60*60*24*30); 
	return parseInt(((((Age/1000)/60)/60)/24)/365.25,10); 
}


var validarPagoComunidades = function (){
	var retorno
    var url = '/appjob/jobs';
    var pars = "action=ValidaComunidades"+
                     "&user_id="+userData.userid+
                     "&product_id="+ecomProduct;
    new Ajax.Request(
                     url,{
                           method:'POST',
                           parameters: pars,
                           encoding: characterEncoding,
                           asynchronous:false,
                           onSuccess : function(resp){
                                             var repuesta = resp.responseJSON || "no response text";
                                             retorno = repuesta.comunidad;
                     					}
                     }
                     );
    return retorno;
}

var guardaPostulacion = function(respuestas){
	var url = '/appjob/jobs';
	var pars =  "action=GuardaPostulacion"+
			"&avisoRespuesta0="+encodeURIComponent(respuestas[0])+
			"&avisoRespuesta1="+encodeURIComponent(respuestas[1])+
			"&avisoRespuesta2="+encodeURIComponent(respuestas[2])+
			"&avisoRespuesta3="+encodeURIComponent(respuestas[3])+
			"&avisoRespuesta4="+encodeURIComponent(respuestas[4])+
			"&avisoRespuesta5="+encodeURIComponent(respuestas[5])+
			"&codigoAviso="+codigoAviso;

	if (fromWoman==1){pars+="&key=mujerlaborum";}
	
	if (fromPTIC==1){pars+="&key=profesionalestic";	}

	$('avisoLightbox1').startWaiting('bigWaiting');
	new Ajax.Request(
	url,
	{
		method:'POST',
		parameters: pars,
		encoding: characterEncoding,
		onSuccess : doneGuardaPostulacion				
	});
}
var postular = function(preguntasLength){
	var respuestas = new Array();
	var error = 0;
	var k=0;
	var respuesta0 = "";
	var respuesta1 = "";
	var respuesta2 = "";
	var respuesta3 = "";
	var respuesta4 = "";
	var respuesta5 = "";
	respuestas[0]= "";
	respuestas[1]= "";
	respuestas[2]= "";
	respuestas[3]= "";
	respuestas[4]= "";
	respuestas[5]= "";

	var errorAllResponses=0;
	 fromWoman = (typeof fromMujer == 'undefined')?"":fromMujer;
	 fromPTIC= (typeof fromTIC == 'undefined')?"":fromTIC;

	if(userData.userid!=0){
		if(userData.personalData==0){
			alert("Para poder postular debe ingresar informaci\u00d3n personal, favor completa tu cv");
		}else if(userData.totalEstudios==0){
			alert("Para poder postular debes completar tu cv, agrega un estudio.");		
		
		}else{
			if(fromWoman!= "" || fromPTIC!="" ){
				var pagoOk = validarPagoComunidades();
				if(pagoOk=="0"){
					window.scroll(0,0);
					mensajeAlerta="Para poder postular a esta oferta debes haber cancelado tu suscripci\u00F3n";
					switchLightBox("Alerta",'/lightbox/mensajeAlerta.html',450,200);
				}else
					guardaPostulacion(respuestas);
			}
			
			if (preguntasLength>0){
				for (var i=0; i < preguntasLength; i++) {
					valueParam=$('textoArea'+i).value;
					valueParam=valueParam.trim();
					if(valueParam.length==0){
						errorAllResponses = 1;
					}else{
						respuestas[i]=valueParam;
					}
				}
				
				if (errorAllResponses==1) alert("Para postular a esta oferta debes responder todas las preguntas");
				if ($('textoArea0')!=null) $('textoArea0').focus();
			}
			
			
				
			if (errorAllResponses==0) {
				 guardaPostulacion(respuestas);
			}
		}
	} else {
		if(fromWoman!= "" || fromPTIC!= "" ){			
			mensajeAlerta="Debes ingresar a tu cuenta para poder postular";
			switchLightBox("Alerta",'/lightbox/mensajeAlerta.html',400,190);
		}else{
			//switchLightBox('REGISTRO PARA POSTULAR','/lightbox/loginBox.html', 450, 400);
			alert("Favor debes logearte a nuestro sitio");
			return false;
		}
	}
}



var enviar =function(){
	/*new Ajax.Updater('confirmacion','/lightbox/envioOferta.html', {evalScripts: true });*/
	$('avisoLightbox1').style.display='none';
	switchLightBox('Confirmacion','/lightbox/envioOferta.html', 800, 650);
	
	return false;
}
 doneGuardaPostulacion=function(resp){
	
$('avisoLightbox1').stopWaiting();

	var dataAviso = resp.responseJSON || "no response text";
	if (dataAviso.goToLogin==1)
	    alert("Para postular a esta oferta debes responder todas las preguntas.");
	else{
		if (dataAviso.estadoPostulacion==0)
		    alert("Ya est\u00e1s postulando a esta oferta");
		else if(dataAviso.retorno!=undefined){
			if (dataAviso.estadoPostulacion==1){

				var x = screenWidth()*0.07;	
				var y = screenHeight()*0.06;	
			
			
				$('confirmacion').style.display = 'block';
			 	$('confirmacion').style.left = x + 'px';
			 	$('confirmacion').style.top = y + 'px'; 
			 	
			 			 
			 	
				$('confirmacion').innerHTML ="" +
						"<div>"+
						"<h3>Confirmaci&oacute;n Postulaci&oacute;n</h3>" +
							"<p>Tu postulaci&oacute;n al aviso ha sido enviada con &eacute;xito</p>" +
							"<p>Te recordamos que desde este momento, es la empresa quien revisar&aacute; y seleccionar&aacute; a los postulantes que mejor cumplan con el perfil requerido para el cargo.</p>" +
							"<p>De esta forma, si resultas o no seleccionado(a), es dicha empresa la responsable de tomar contacto contigo para comunic&aacute;rtelo.</p>" +
							"<p>En caso de cualquier consulta, te agradeceremos completar el formulario de contacto.</p>" +
							"<p>Gracias por confiar en nosotros</p>" +
							"<p>Laborum.com - Todos los derechos reservados 2008-2010</p>" +
							"<br></br>" +							
							"<div align=\"center\"><a href=\"#\" onClick=\"cerrarConfirmacion();\"><img  src=\"http://resource.laborum.cl/css/i/btn-cerrar.gif\" border=\"0\"/></a></div>" +
							"<br></br>" +
							"<br></br>" +
							"<div style=\"visibility: hidden;\">" +
								"<img src=\"/imagenes/dot.gif\" name=\"cert_Pivot\" id=\"cert_Pivot\" width=\"1\" height=\"1\" alt=\"\" />" +
								"<script language=\"JavaScript1.4\" src=\"http://www.laborum.cl/certifica/certifica-js14.js\"></script>" +
								"<script type= \"text/javascript\" src=\"http://www.laborum.cl/certifica/certifica.js\"></script>" +
								"<script type= \"text/javascript\">" +
								"var oferta= codigoAviso;" +
								"cert_registerHit(15468, '/home/postulacion/'+oferta);" +
								"</script>" +
							"</div>	" +
						"</div>";			
				
				/*
				new Ajax.Updater('confirmacion','/lightbox/ofertaConfirmacionPostulacion.html', {evalScripts: true });
				$('spaceId').style.display='none';
				$('avisoLightbox1').style.display='none';
*/
			}else{
				alert("Lamentamos informarle que esta oferta se encuentra expirada.");
			}	
		}
	}
}



// ************************************
var calculaEdad=function(yr, mon, day){
	var one_day=1000*60*60*24
	var one_month=1000*60*60*24*30
	var one_year=1000*60*60*24*30*12
	today=new Date();
	var pastdate=new Date(yr, mon-1, day);
	var countunit="years";
	var decimals=0;
	var rounding="rounddown";
	finalunit=(countunit=="days")? one_day : (countunit=="months")? one_month : one_year;
	decimals=(decimals<=0)? 1 : decimals*10;
	yearspast=today.getFullYear()-yr-1
	tail=(today.getMonth()>mon-1 || today.getMonth()==mon-1 && today.getDate()>=day)? 1 : 0
	pastdate.setFullYear(today.getFullYear())
	pastdate2=new Date(today.getFullYear()-1, mon-1, day)
	tail=(tail==1)? tail+Math.floor((today.getTime()-pastdate.getTime())/(finalunit)*decimals)/decimals : Math.floor((today.getTime()-pastdate2.getTime())/(finalunit)*decimals)/decimals
	return yearspast+tail;
}




//***************************************
// Funciones para Calculadora


var elementoEsVacio =function(idElemento,alerta) {
			if($(idElemento).value.length == 0)
				{
				alert(alerta);
				$(idElemento).focus();
				return true;
				}
			return false;
	}
var elementoEsEnteroCalc =function(idElemento,alerta) {
			valor = replaceAll($(idElemento).value,".","");
			if(!numerico.test(valor))
				{
				alert(alerta);
				$(idElemento).focus();
				return true;
				}
			return false;
	}

var elementoEsEntero =function(idElemento,alerta) {
			valor = $(idElemento).value.trim();
			if(!numerico.test(valor))
				{
				alert(alerta);
				$(idElemento).focus();
				return true;
				}
			return false;
	}
	
function replaceAll(text, strA, strB){
    while ( text.indexOf(strA) != -1)
    {
       text = text.replace(strA,strB);
    }
    return text;
}

function reemplazarCaracteres(texto){
	if (texto==null){
		return "";
	}

	if (texto==undefined){
		return "";
	}

	if (texto.trim()==""){
		return "";
	}

	texto = texto.toLowerCase();
	texto = replaceAll(texto,"á","a");
	texto = replaceAll(texto,"é","e");
	texto = replaceAll(texto,"í","i");
	texto = replaceAll(texto,"ó","o");
	texto = replaceAll(texto,"ú","u");

	texto = replaceAll(texto,"à","a");
	texto = replaceAll(texto,"è","e");
	texto = replaceAll(texto,"ì","i");
	texto = replaceAll(texto,"ò","o");
	texto = replaceAll(texto,"ù","u");

	texto = replaceAll(texto,"ä","a");
	texto = replaceAll(texto,"ë","e");
	texto = replaceAll(texto,"ï","i");
	texto = replaceAll(texto,"ö","o");
	texto = replaceAll(texto,"ü","u");
	
	texto = replaceAll(texto,"ñ","n");
	
	/*
	texto = replaceAll(texto,"'"," ");
	texto = replaceAll(texto,"-"," ");
	texto = texto.replace("+"," ");
	texto = texto.replace("."," ");
	texto = texto.replace(","," ");
	texto = texto.replace("&"," ");
	texto = replaceAll(texto,"~"," ");
	texto = texto.replace("("," ");
	texto = texto.replace(")"," ");
	texto = replaceAll(texto,"^"," ");
	texto = texto.replace("["," ");
	texto = texto.replace("]"," ");
	texto = replaceAll(texto,"_"," ");
	texto = replaceAll(texto,"#"," ");
	texto = replaceAll(texto,"$"," ");
	texto = replaceAll(texto,"<"," ");
	texto = replaceAll(texto,">"," ");
	texto = replaceAll(texto,"="," ");
	texto = replaceAll(texto,"¡"," ");
	texto = replaceAll(texto,"!"," ");
	texto = texto.replace("?"," ");
	texto = texto.replace("*"," ");
	texto = texto.replace("¿"," ");
	texto = texto.replace("{"," ");
	texto = texto.replace("}"," ");
	texto = replaceAll(texto,"`"," ");
	texto = replaceAll(texto,"´"," ");
	
	texto = replaceAll(texto,":"," ");
	texto = replaceAll(texto,"|","");
	texto = replaceAll(texto,"¬","");
	*/

	return texto.trim();
}

var elementoEsNulo =function(idElemento,alerta) {
			if($(idElemento).value==0)
				{
				alert(alerta);
				$(idElemento).focus();
				return true;
				}
			return false;
	}

var elementoEsNegativo =function(idElemento,alerta) {
	if(!numerico.test($(idElemento).value)){
			if(idElemento < 0)
				{
				alert(alerta);
				$(idElemento).focus();
				return true;
				}
			}
			return false;
	}


var MultiDimensionalArray= function(iRows,iCols)
{
var i;
var j;
   var a = new Array(iRows);
   for (i=0; i < iRows; i++)
   {
       a[i] = new Array(iCols);
       for (j=0; j < iCols; j++)
       {
           a[i][j] = "";
       }
   }
   return(a);
}



// ENCUESTA
var buscarEnCadenas=function(valorCookie, surveyId) {
	var arrayValorCookie = valorCookie.split(',');
	for(var i=0;i < arrayValorCookie.length;i++) {
		var vCookie = arrayValorCookie[i];
		if(vCookie.indexOf(surveyId)==0){
			return true;
		}
	}
	return false;
}
var checkInCookie=function(cookieName,surveyId)
{
	var valorCookie=ReadCookie(cookieName);
	if(valorCookie.length==0) return false;
	return buscarEnCadenas(valorCookie,surveyId);
}
var responderEncuesta=function(surveyId)
{
	if(!checkInCookie("LABORUM_ENCUESTA",surveyId)){
		var arrayOptions = new Array();
		var iCount = 0;
		var labelIds = $F('labelIds');
		var mySplitResult = labelIds.split(",");
		var entro = 0;
		for(i = 0; i < mySplitResult.length; i++){
			var value = $RF("option_"+mySplitResult[i]);
			if(value==null){
				entro=1;
			}else{
				arrayOptions[iCount++]=value;
			}
		}
		if(entro==1){
			alert("Debe responder la encuesta");
		}else{
			enviarRespuesta(surveyId,labelIds,arrayOptions.toString());
		}
	}else{
		window.location = "/encuesta.html?surveyId="+surveyId;
	}
}
var responderEncuestaEmpresa=function(surveyId)
{
	if(!checkInCookie("LABORUM_ENCUESTA",surveyId)){
		var arrayOptions = new Array();
		var iCount = 0;
		var labelIds = $F('labelIds');
		//alert(labelIds);
		var mySplitResult = labelIds.split(",");
		var entro = 0;
		for(i = 0; i < mySplitResult.length; i++){
			var value = $RF("option_"+mySplitResult[i]);
			if(value==null){
				entro=1;
			}else{
				arrayOptions[iCount++]=value;
			}
		}
		if(entro==1){
			lbMensajeAlerta("Debe responder la encuesta");
		}else{
			enviarRespuestaEmpleador(surveyId,labelIds,arrayOptions.toString());
		}
	}else{
		window.location = "/empleadores/encuesta.html?surveyId="+surveyId;
	}
}
var enviarRespuesta=function(surveyId,labelIds,optionIds)
{
	var url = '/appjob/jobs';
	var pars = "action=SurveyRegisterOptions&encuesta="+surveyId+"&pregunta="+labelIds+"&idOpcion="+optionIds;
	new Ajax.Request(
		url,
		{
			method:'POST',
			parameters: pars,
			encoding: characterEncoding,
			onSuccess : responseSurvey
		}
	);
}
var enviarRespuestaEmpleador=function(surveyId,labelIds,optionIds)
{
	var url = '/appjob/jobs';
	var pars = "action=SurveyRegisterOptions&encuesta="+surveyId+"&pregunta="+labelIds+"&idOpcion="+optionIds;
	new Ajax.Request(
		url,
		{
			method:'POST',
			parameters: pars,
			encoding: characterEncoding,
			onSuccess : responseSurveyEmpleador
		}
	);
}
var responseSurvey=function(resp){
	var data = resp.responseJSON || "no response text";
	if (data.bError == 0) {
		window.location = "/encuesta.html?surveyId="+data.surveryId;
	}else{
		if(data.bError == 1){
			if (data.error!=undefined) {$('errorEncuesta').innerHTML = data.error;};
		}
	}
}
var responseSurveyEmpleador=function(resp){
	var data = resp.responseJSON || "no response text";
	if (data.bError == 0) {
		window.location = "/empleadores/encuesta.html?surveyId="+data.surveryId;
	}else{
		if(data.bError == 1){
			if (data.error!=undefined) {$('errorEncuesta').innerHTML = data.error;};
		}
	}
}


var limiteTexto=function(que,cuanto,contText)
{
	var v=que.value
	if(v.length>cuanto)
		que.value=v.substring(0,cuanto)
	else
		$(contText).value=cuanto-v.length
}

function setRF(el,value)
{	

	var no = el;
	var el = document.getElementById(el);
	var el = $(el).form;
	for(i = 0; i < $(el).getInputs('radio').length; i++) {
		if($(el).getInputs('radio')[i].name==no)
		if(($(el).getInputs('radio')[i].value)==value ){
			$(el).getInputs('radio')[i].checked=true;
		}
	}
}
var lbMensajeAlerta=function(data) {
	mensajeAlerta=data;
	switchLightBox("Alerta",'/lightbox/mensajeAlerta.html',300,200);
}
var lbMensajeAlertaXY=function(data,x,y) {
	mensajeAlerta=data;
	switchLightBox("Alerta",'/lightbox/mensajeAlerta.html',x,y)
}
var lbMensajeAlertaForm=function(data,campo) {
	mensajeAlerta=data;
	campoDesplegar=campo;
	switchLightBox("Alerta",'/lightbox/mensajeAlertaForm.html',300,200)
}
var lbMensajeAlertaFormAceptar=function(data,campo) {
	mensajeAlerta=data;
	campoDesplegar=campo;
	switchLightBox("Alerta",'/lightbox/mensajeAlertaFormAceptar.html',300,200)
}
var lbMensajeGo=function(titulo,data,botonTitulo,urlGo) {
	mensajeAlerta=data;
	botonTituloHtml=botonTitulo;
	urlGoHtml=urlGo;
	switchLightBox(titulo,'/lightbox/mensajeGo.html',300,200)
}
function fxTrim(cadena)
{
	for(i=0; i<cadena.length; )
	{
		if(cadena.charAt(i)==" ")
			cadena=cadena.substring(i+1, cadena.length);
		else
			break;
	}

	for(i=cadena.length-1; i>=0; i=cadena.length-1)
	{
		if(cadena.charAt(i)==" ")
			cadena=cadena.substring(0,i);
		else
			break;
	}
	return cadena;
}





var numeroMes=function(numeroMes) {
	if(isNaN(numeroMes)) return "01";
	if(numeroMes>12) return "12";
	if(numeroMes<1) return "01";
	if(numeroMes<10) return "0"+numeroMes;
	return numeroMes;
}

var numeroAnno=function(numeroAnno) {
	if(isNaN(numeroAnno)) return "2005";
	if(numeroAnno>2050) return "2005";
	if(numeroAnno<1900) return "1980";
	return numeroAnno;
}
function formatAsMoney(mnt) {
    mnt -= 0;
    mnt = (Math.round(mnt*100))/100;
    return (mnt == Math.floor(mnt)) ? mnt + '.00' 
              : ( (mnt*10 == Math.floor(mnt*10)) ? 
                       mnt + '0' : mnt);
}

function stripHTML(string){
//	return s.replace(/\\&/g, '&amp;').replace(/\\</g, '&lt;').replace(/\\>/g, '&gt;').replace(/\\t/g, '&nbsp;&nbsp;&nbsp;').replace(/\\n/g, '<br />');
	var matchTag = /<(?:.|\s)*?>/g;
	return string.replace(matchTag, "");
}


function saltoLineaBR(string){
	string = string.replace(/\r\n/g,'<br>');
	string = string.replace(/\r/g,'<br>');
	string = string.replace(/\n/g,'<br>');
	return string;
}


changeClassImpar= function(id,flag){

		if (flag){
			$(id).className="bordePunteado impar2";
			$(id+'_2').className="impar2";
		}else{
			$(id).className="bordePunteado impar";
			$(id+'_2').className="impar";
		}
	}	
	
changeClassPar= function(id,flag){

		if (flag){
			$(id).className="bordePunteado impar2";
			$(id+'_2').className="impar2";
		}else{
			$(id).className="bordePunteado ";
			$(id+'_2').className="";
		}
		
}


/*************************************************/
/***Agrega cambio de clase para Buscador MisCVs***/
/*************************************************/
marcaSelImpar= function(id,flag){

	if (flag){
		$(id+'chk').className="bordePunteadoCv impar2Cv";
		$(id+'chk_2').className="impar2Cv";
	}else{
		$(id+'chk').className="bordePunteadoCv imparCv";
		$(id+'chk_2').className="imparCv";
	}
}
marcaSelPar= function(id,flag){

	if (flag){
		$(id+'chk').className="bordePunteadoCv impar2Cv";
		$(id+'chk_2').className="impar2Cv";
	}else{
		$(id+'chk').className="bordePunteadoCv ";		
		$(id+'chk_2').className="";	
	}
}

getSelected =function()
{
 ListaSeleccion = "";
 for(l=0;l<$('comunaId_r').length;l++)
 {
    if($('comunaId_r').options[l].selected == true)
    {
		if(ListaSeleccion == "")
   			ListaSeleccion += $('comunaId_r').options[l].value;
     	else
  			ListaSeleccion += ","+$('comunaId_r').options[l].value; 
    }
  }
   return ListaSeleccion;
}

cambiaFondoPasosCvEnt = function(paso, opacity, idElement){	
	
	if(opacity == 1){			   
		
		try	{			
			$(idElement).filters.alpha.opacity= '40';
			hideElements($(idElement),"select");
			hideElements($(idElement),"h2");
			hideElements($(idElement),"span");
			hideElements($(idElement),"a");
			hideElements($(idElement),"caption");
			
		}
		catch(e){
			
			$(idElement).style.opacity= '0.4';}	
	}
	else{
		
		try{
			$(idElement).filters.alpha.opacity= '100';
			showElements($(idElement),"select");
			showElements($(idElement),"h2");
			showElements($(idElement),"span");
			showElements($(idElement),"a");
			showElements($(idElement),"caption");
		}
		catch(e){
			$(idElement).style.opacity= '1';}
	}
		
	if(paso==2){
		$('pasosCv').style.backgroundPosition = '0px -49px';}
	if(paso==1){
		$('pasosCv').style.backgroundPosition = '0px 0px';}
	if(paso==3){
		$('pasosCv').style.backgroundPosition = '0px -99px';}
	if(paso==4){
		$('pasosCv').style.backgroundPosition = '0px -147px';}
	
}

cambiaFondoPasos = function(paso, opacity,idElement){	
	
	if(opacity == 1){			   
		
		try	{			
			$(idElement).filters.alpha.opacity= '40';
			hideElements($(idElement),"select");
			hideElements($(idElement),"h2");
			hideElements($(idElement),"span");
			hideElements($(idElement),"a");
			hideElements($(idElement),"caption");
			
		}
		catch(e){
			
			$(idElement).style.opacity= '0.4';}	
	}
	else{
		
		try{
			$(idElement).filters.alpha.opacity= '100';
			showElements($(idElement),"select");
			showElements($(idElement),"h2");
			showElements($(idElement),"span");
			showElements($(idElement),"a");
			showElements($(idElement),"caption");
		}
		catch(e){
			$(idElement).style.opacity= '1';
		}
	}
		
	if(paso==2){
		$('pasosCv').style.backgroundPosition = '0px -50px';}
	if(paso==1){
		$('pasosCv').style.backgroundPosition = '0px 0px';}
	if(paso==3){
		$('pasosCv').style.backgroundPosition = '0px -100px';}
	
}


hideElements = function(section,element){
	var elements = section.getElementsByTagName(element); 
	for (var i = 0; i < elements.length; i++) 
	   elements[i].style.visibility = "hidden"; 
	   
}

showElements = function(section,element){
	var elements = section.getElementsByTagName(element); 
	for (var i = 0; i < elements.length; i++) 
	   elements[i].style.visibility = "visible"; 	
}


/**********************************/
/***Funcion validadora RUT plano***/
/**********************************/
function revisarDigito( dvr )
{	
	dv = dvr + ""	
	if ( dv != '0' && dv != '1' && dv != '2' && dv != '3' && dv != '4' && dv != '5' && dv != '6' && dv != '7' && dv != '8' && dv != '9' && dv != 'k'  && dv != 'K')	
	{		
		alert("Debe ingresar un digito verificador v\u00e1lido");		
				
		rut.select();		
		return false;	
	}	
	return true;
}

function revisarDigito2( crut )
{	
	
	largo = crut.length;	
	if ( largo < 2 )	
	{		
		alert("Debe ingresar el rut completo")		
				
		rut.select();		
		return false;	
	}	
	
	if ( largo > 2 )	
		
		var rut = crut.substring(0, largo - 1);	
		
	else		
		rut = crut.charAt(0);	
		dv = crut.charAt(largo-1);	
		revisarDigito( dv );	

	if ( rut == null || dv == null )
		return 0	

	var dvr = '0'	
	suma = 0	
	mul  = 2	
	
	for (i= rut.length -1 ; i >= 0; i--)	
	{	
		suma = suma + rut.charAt(i) * mul		
		if (mul == 7)			
			mul = 2		
		else    			
			mul++	
	}	
	res = suma % 11	
	if (res==1)		
		dvr = 'k'	
	else if (res==0)		
		dvr = '0'	
	else	
	{		
		dvi = 11-res		
		dvr = dvi + ""	
	}
	if ( dvr != dv.toLowerCase() )	
	{		
		alert('Ingrese un Rut v\u00e1lido');	
		return false;
	}

	return true
}

function ValRutCompleto(texto)
{
	
	var rut = ""
	var tmpstr = "";	
	for ( i=0; i < texto.length ; i++ )		
		if ( texto.charAt(i) != ' ' && texto.charAt(i) != '.' && texto.charAt(i) != '-' )
			tmpstr = tmpstr + texto.charAt(i);	
	texto = tmpstr;	
	largo = texto.length;	
	
	if ( largo < 2 )	
	{		
		alert("Debe ingresar el RUT correctamente")				
		return false;	
	}	

	for (i=0; i < largo ; i++ )	
	{			
		if ( texto.charAt(i) !="0" && texto.charAt(i) != "1" && texto.charAt(i) !="2" && texto.charAt(i) != "3" && texto.charAt(i) != "4" && texto.charAt(i) !="5" && texto.charAt(i) != "6" && texto.charAt(i) != "7" && texto.charAt(i) !="8" && texto.charAt(i) != "9" && texto.charAt(i) !="k" && texto.charAt(i) != "K" )
 		{			
			alert("El valor ingresado no corresponde a un RUT valido");	
			$('rut').value=""
			return false;		
		}	
	}	

	var invertido = "";	
	for ( i=(largo-1),j=0; i>=0; i--,j++ )		
		invertido = invertido + texto.charAt(i);	
	var dtexto = "";	
	dtexto = dtexto + invertido.charAt(0);	
	dtexto = dtexto + '-';	
	cnt = 0;	

	for ( i=1,j=2; i<largo; i++,j++ )	
	{		
		//alert("i=[" + i + "] j=[" + j +"]" );		
		if ( cnt == 3 )		
		{			
			dtexto = dtexto + '';			
			j++;			
			dtexto = dtexto + invertido.charAt(i);			
			cnt = 1;		
		}		
		else		
		{				
			dtexto = dtexto + invertido.charAt(i);			
			cnt++;		
		}	
	}	

	invertido = "";	
	
	for ( i=(dtexto.length-1),j=0; i>=0; i--,j++ )		
		var invertido = invertido + dtexto.charAt(i);	

	//window.document.form1.rut.value = invertido.toUpperCase()		
	
	var rut = invertido.toUpperCase()
	$('rut').value=rut;
	
	if ( revisarDigito2(texto) )		
		return true;	
	
	return false;
}

function avisoCvMovido(status,idform,contRec){
	var estadoCv ="";
	var enviaMensaje=0;
	if(status==1) estadoCv='"DISPONIBLE(S)"';
	if(status==2) estadoCv='"SELECCIONADO(S)"';
	if(status==3) estadoCv='"ELIMINADO(S)"';

	if(idform!=undefined){
		var cantCvs=1;
		
		if(idform!='FormCvs'){
		//	cantCvs=(obtenerTotPostulantes(idform));
		}

		//if(cantCvs>1){
			alert("Cv(s) seleccionado(s) ha(n) sido movido(s) a: "+estadoCv+".");
		//}else{
		//	alert("Cv(s) ha sido movido a: "+estadoCv+".");
		//}
		enviaMensaje=1;
	}

	if(contRec!=undefined){
		if(contRec>1){
			alert(contRec+" Cvs han sido movidos a: "+estadoCv+".");
		}else{
			alert(contRec+" Cv ha sido movido a: "+estadoCv+".");
		}
		enviaMensaje=1;
	}

	if(enviaMensaje==0){
		alert("El Cv se encuentra "+estadoCv);
	}
}


function numMovido(status,estadoCv,cvs,_idAviso,_titulo,_estado,_fecha,activePageJob,_estAnt,_anioAnt,_dele,_aval,_sele,rowTotal){
	var _sel="";
	var _del="";
	var _ava="";
	if(estadoCv==1){	/*DISPONIBLE*/
		if(status==2){	/Seleccionado/
			_sel=parseInt(document.getElementById('cvsSelected').firstChild.nodeValue) + cvs;
			_ava=parseInt(document.getElementById('cvsAvalaible').firstChild.nodeValue) - cvs;
			window.location="indexListaCvs.html?idAvisoSeleccionado="+_idAviso+"&estadoCv=2&titulo="+_titulo+"&estado="+_estado+"&fechaPub="+_fecha+"&paginaAnterior="+activePageJob+"&estadoAnterior="+_estAnt+"&anioAnterior="+_anioAnt+"&eliminados="+_dele+"&disponibles="+_ava+"&seleccionados="+_sel;	
		}
		if(status==3){	/Eliminado/
			_del=parseInt(document.getElementById('cvsDeleted').firstChild.nodeValue) + cvs;
			_ava=parseInt(document.getElementById('cvsAvalaible').firstChild.nodeValue) - cvs;
			window.location="indexListaCvs.html?idAvisoSeleccionado="+_idAviso+"&estadoCv=3&titulo="+_titulo+"&estado="+_estado+"&fechaPub="+_fecha+"&paginaAnterior="+activePageJob+"&estadoAnterior="+_estAnt+"&anioAnterior="+_anioAnt+"&eliminados="+_del+"&disponibles="+_ava+"&seleccionados="+_sele;
		}
	}
	if(estadoCv==2){	/*SELECCIONADO*/
		if(status==1){	/Disponible/
			_sel=parseInt(document.getElementById('cvsSelected').firstChild.nodeValue) - cvs;
			_ava=parseInt(document.getElementById('cvsAvalaible').firstChild.nodeValue) + cvs;
			window.location="indexListaCvs.html?idAvisoSeleccionado="+_idAviso+"&estadoCv=1&titulo="+_titulo+"&estado="+_estado+"&fechaPub="+_fecha+"&paginaAnterior="+activePageJob+"&estadoAnterior="+_estAnt+"&anioAnterior="+_anioAnt+"&eliminados="+_dele+"&disponibles="+_ava+"&seleccionados="+_sel;
		}
		if(status==3){	/Eliminado/
			_sel=parseInt(document.getElementById('cvsSelected').firstChild.nodeValue) - cvs;
			_del=parseInt(document.getElementById('cvsDeleted').firstChild.nodeValue) + cvs;
			window.location="indexListaCvs.html?idAvisoSeleccionado="+_idAviso+"&estadoCv=3&titulo="+_titulo+"&estado="+_estado+"&fechaPub="+_fecha+"&paginaAnterior="+activePageJob+"&estadoAnterior="+_estAnt+"&anioAnterior="+_anioAnt+"&eliminados="+_del+"&disponibles="+_aval+"&seleccionados="+_sel;
		}
	}
	if(estadoCv==3){	/*ELIMINADO*/
		if(status==1){	/Disponible/
			_sel=parseInt(document.getElementById('cvsAvalaible').firstChild.nodeValue) + cvs;
			_del=parseInt(document.getElementById('cvsDeleted').firstChild.nodeValue) - cvs;
			window.location="indexListaCvs.html?idAvisoSeleccionado="+_idAviso+"&estadoCv=1&titulo="+_titulo+"&estado="+_estado+"&fechaPub="+_fecha+"&paginaAnterior="+activePageJob+"&estadoAnterior="+_estAnt+"&anioAnterior="+_anioAnt+"&eliminados="+_del+"&disponibles="+_sel+"&seleccionados="+_sele;
		}
		if(status==2){	/Seleccionado/
			_sel=parseInt(document.getElementById('cvsSelected').firstChild.nodeValue) + cvs;
			_del=parseInt(document.getElementById('cvsDeleted').firstChild.nodeValue) - cvs;
			window.location="indexListaCvs.html?idAvisoSeleccionado="+_idAviso+"&estadoCv=2&titulo="+_titulo+"&estado="+_estado+"&fechaPub="+_fecha+"&paginaAnterior="+activePageJob+"&estadoAnterior="+_estAnt+"&anioAnterior="+_anioAnt+"&eliminados="+_del+"&disponibles="+_aval+"&seleccionados="+_sel;
		}
	}
}

function numMovidoBodega(idform,status,estadoCv, estadoCvActual){
	var totalPro 	="";
	var totalPos 	="";
	totalPro=(obtenerProactivos(idform));		/*Total de proactivos*/
	totalPos=(obtenerTotPostulantes(idform));	/*Total postulantes*/
	empresa			="";
	proactivas		="";
	seleccionados	="";
	eliminados		="";
	eCv				=estadoCvActual;
	eStc			="";
	if((estadoCv==0) && (paramSTC==0)){		/*POSTULANTES EMPRESA*/
		if(status==1){						/Si apreto Disponible/
			empresa			= valorEmpresa;
			proactivas		= valorProactivo;
			seleccionados	= valorSeleccionado;
			eliminados		= valorEliminado;
			//eCv				= 0;
			eStc			= 0;	
		}	
		if(status==2){						/Si apreto Seleccionar/
			empresa			= rowTotal - totalPos;
			proactivas		= parseInt(document.getElementById('numPstProactivo').firstChild.nodeValue) + totalPro;
			seleccionados	= parseInt(document.getElementById('numPstSeleccionado').firstChild.nodeValue)+ totalPos;
			eliminados		= valorEliminado;
			//eCv				= 2;
			eStc			= 2;
		}	
		if(status==3){						/Si apreto Eliminar/
			empresa			= rowTotal - totalPos;
			proactivas		= parseInt(document.getElementById('numPstProactivo').firstChild.nodeValue) + totalPro;
			seleccionados	= valorSeleccionado;
			eliminados		= parseInt(document.getElementById('numPstEliminado').firstChild.nodeValue)+ totalPos;
			//eCv				= 3;
			eStc			= 2;
		}	
	}
	if((estadoCv==0) && (paramSTC==1)){		/*POSTULACION PROACTIVA*/
		if(status==1){						/Si apreto Disponible/
			empresa			= valorEmpresa;
			proactivas		= valorProactivo;
			seleccionados	= valorSeleccionado;
			eliminados		= valorEliminado;
			//eCv				= 0;
			eStc			= 1;	
		}	
		if(status==2){						/Si apreto Seleccionar/
			empresa			= valorEmpresa;
			proactivas		= parseInt(document.getElementById('numPstProactivo').firstChild.nodeValue) - totalPro;
			seleccionados	= parseInt(document.getElementById('numPstSeleccionado').firstChild.nodeValue)+ totalPos;
			eliminados		= valorEliminado;
			//eCv				= 2;
			eStc			= 2;
		}	
		if(status==3){						/Si apreto Eliminar/
			empresa			= valorEmpresa;
			proactivas		= parseInt(document.getElementById('numPstProactivo').firstChild.nodeValue) - totalPro;
			seleccionados	= valorSeleccionado;
			eliminados		= parseInt(document.getElementById('numPstEliminado').firstChild.nodeValue)+ totalPos;
			//eCv				= 3;
			eStc			= 2;
		}	
	}
	if((estadoCv==2) && (paramSTC==2)){		/*SELECCIONADOS*/
		if(status==1){						/Si apreto Disponible/
			empresa			= parseInt(document.getElementById('numPstEmpresa').firstChild.nodeValue)+ (totalPos-totalPro);
			proactivas		= parseInt(document.getElementById('numPstProactivo').firstChild.nodeValue) + totalPro;
			seleccionados	= parseInt(document.getElementById('numPstSeleccionado').firstChild.nodeValue) - totalPos;
			eliminados		= valorEliminado;
			//eCv				= 0;
			eStc			= 2;
			//if(totalPro>0) alert("Se ha(n) movido :"+" "+totalPro+" CV(s) a Postulaciones Proactivas");
		}	
		if(status==2){						/Si apreto Seleccionar/
			empresa			= valorEmpresa;
			proactivas		= valorProactivo;
			seleccionados	= valorSeleccionado;
			eliminados		= valorEliminado;
			//eCv				= 2;
			eStc			= 2;
		}	
		if(status==3){						/Si apreto Eliminar/
			empresa			= valorEmpresa;
			proactivas		= valorProactivo
			seleccionados	= parseInt(document.getElementById('numPstSeleccionado').firstChild.nodeValue)- totalPos;
			eliminados		= parseInt(document.getElementById('numPstEliminado').firstChild.nodeValue)+ totalPos;
			//eCv				= 3;
			eStc			= 2;
		}	
	}
	if((estadoCv==3) && (paramSTC==2)){		/*ELIMINADOS*/
		if(status==1){						/Si apreto Disponible/
			empresa			= parseInt(document.getElementById('numPstEmpresa').firstChild.nodeValue)+ (totalPos-totalPro);
			proactivas		= parseInt(document.getElementById('numPstProactivo').firstChild.nodeValue) + totalPro;
			seleccionados	= valorSeleccionado
			eliminados		= parseInt(document.getElementById('numPstEliminado').firstChild.nodeValue) - totalPos;
			//eCv				= 0;
			eStc			= 2;
			//if(totalPro>0) alert("Se ha(n) movido :"+" "+totalPro+" CV(s) a Postulaciones Proactivas");
		}	
		if(status==2){						/Si apreto Seleccionar/
			empresa			= valorEmpresa;
			proactivas		= valorProactivo;
			seleccionados	= parseInt(document.getElementById('numPstSeleccionado').firstChild.nodeValue) + totalPos;
			eliminados		= parseInt(document.getElementById('numPstEliminado').firstChild.nodeValue) - totalPos;
			//eCv				= 2;
			eStc			= 2;
		}	
	}
	if((estadoCv==0) && (paramSTC==2)){		/TOTAL (Es la suma de Psts. Empresa + Psts.Proactivas )/
		if(status==1){						/Si apreto Disponible/
			empresa			= valorEmpresa;
			proactivas		= valorProactivo;
			seleccionados	= valorSeleccionado
			eliminados		= valorEliminado;
			//eCv				= 0;
			eStc			= 2;
			//if(totalPro>0) alert("Se ha(n) movido :"+" "+totalPro+" CV(s) a Postulaciones Proactivas");
		}	
		if(status==2){						/Si apreto Seleccionar/
			empresa			= parseInt(document.getElementById('numPstEmpresa').firstChild.nodeValue)+ (totalPos-totalPro);
			proactivas		= parseInt(document.getElementById('numPstProactivo').firstChild.nodeValue) - totalPro;
			seleccionados	= parseInt(document.getElementById('numPstSeleccionado').firstChild.nodeValue) + totalPos;
			eliminados		= valorEliminado;
			//eCv				= 2;
			eStc			= 2;
		}
		if(status==3){						/Si apreto Eliminar/
			empresa			= parseInt(document.getElementById('numPstEmpresa').firstChild.nodeValue)- (totalPos-totalPro);
			proactivas		= parseInt(document.getElementById('numPstProactivo').firstChild.nodeValue) - totalPro;
			seleccionados	= valorSeleccionado
			eliminados		= parseInt(document.getElementById('numPstEliminado').firstChild.nodeValue)+ totalPos;
			//eCv				= 3;
			eStc			= 2;
		}
	}
	/***AQUI ACTUALIZO LA URL CON LOS NUEVOS VALORES PARA VISUALIZAR***/
	window.location="indexListaCvs.html?idAvisoSeleccionado="+idAvisoSeleccionado+"&estadoCv="+eCv+"&titulo="+tituloAviso+"&estado="+estadoAviso+"&fechaPub="+fechaPublicacion+"&stc="+eStc+"&valorEmpresa="+empresa+"&valorProactivo="+proactivas+"&valorSeleccionado="+seleccionados+"&valorEliminado="+eliminados;
	
}



function limpiaCmbCopiar(){		/Funcion limpia combos bodega,email, exel/
	$('filtroMover').value=0;
	$('filtroMover2').value=0;
	$('cmbCargos').value=0;
	$('cmbCargos2').value=0;
}



/*
 * 	Funciones que cargan distintas imagenes al pasar el mouse por encima 
 *  <abaldecchi, 15/04/2009>
 * */
	MM_findObj = function(n, d) { //v4.01
	  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
	    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
	  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
	  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
	  if(!x && d.getElementById) x=d.getElementById(n); return x;
	}
	MM_preloadImages = function() { //v3.0
	  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
	    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
	    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
	}
	MM_swapImgRestore =	function() { //v3.0
	  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
	}
	MM_swapImage = function() { //v3.0
	  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
	   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
	}


/*
 * Funciones para el manejo de fechas
 * <acollao 25/06/2009>
 */
	var obtenerDiasDeDiferencia = function(fechaInicio,fechaFinal) {
		//retorna la cantidad de días de diferencia entre fecha1 y fecha2
		var diff = (fechaFinal - fechaInicio)/(24*60*60*1000); 
		return diff;
	}
	var DatefromUKFormat = function(sUK){
		//Transforma el formato fecha dd/MM/yyyy a MM/dd/yyyy
		var A = sUK.split(/[\\\/]/);
		A = [A[1],A[0],A[2]]; 
		return new Date(Date.parse(A.join('/'))); 
	}
	var sumarDiasAFecha = function(fecha1,dias){
		//Suma los días indicados a fecha1
	    var fecha = DatefromUKFormat(fecha1); 
	    return new Date(fecha.setDate(fecha.getDate()+dias));	
	}
	
	var DateToString = function(fecha){
		var dia = fecha.getDate();
		var mes = fecha.getMonth()+1;
		var anio= fecha.getFullYear();
		var strDia=""+dia;
		var strMes=""+mes;
		var strAnio=""+anio;
		if (dia < 10){strDia="0"+dia;}
		if (mes < 10){strMes="0"+mes;}
		
		return(strDia+"/"+strMes+"/"+strAnio);
	}
/*
 * Funcion para la validacion del uso del buscador de CVs
 */
	var validaBuscadorCVs = function (tipo){
		// tipo 1 ->creacion   ||  tipo 2 -->solo buscar
		var empresasEdicion = new Array("758","87664","12762");
		var empresasBuscarCVs = new Array("174","167","61735","666","71701","1752","1749","21944","192","9150","40229","72000","40195","10258","232","1284");

		// Si se consulta por el permiso para crear cvs (implica buscar)
		if (tipo == '1'){
			for (i=0;i<empresasEdicion.length;i++){
				if (empresasEdicion[i]==userDataEmpresa.usuarioEmpresaId)
					return true;	
			}
		}else{
			/*for (i=0;i<empresasBuscarCVs.length;i++){
				if (empresasBuscarCVs[i]==userDataEmpresa.usuarioEmpresaId)
					return true;
			}*/
			return true;
		}
		return false;
		 
	}
	
	
	function trim (str) {
		/* quita los espacios en blanco */
		var	str = str.replace(/^\s\s*/, ''),
			ws = /\s/,
			i = str.length;
			while (ws.test(str.charAt(--i)));
				return str.slice(0, i + 1);
	}
	
	var screenWidth = function(){
		var screenW = 640;		
		if (parseInt(navigator.appVersion)>3) {
		 screenW = screen.width;	
		}
		else if (navigator.appName == "Netscape"   && parseInt(navigator.appVersion)==3 && navigator.javaEnabled() ) 
		{
		 var jToolkit = java.awt.Toolkit.getDefaultToolkit();
		 var jScreenSize = jToolkit.getScreenSize();
		 screenW = jScreenSize.width;	
		}
		
		return screenW;
	}
	var screenHeight = function(){
		var screenH = 480;
		if (parseInt(navigator.appVersion)>3) {
		 screenH = screen.height;
		}
		else if (navigator.appName == "Netscape"  && parseInt(navigator.appVersion)==3 && navigator.javaEnabled() ) 
		{
			 var jToolkit = java.awt.Toolkit.getDefaultToolkit();
			 var jScreenSize = jToolkit.getScreenSize();
			 screenH = jScreenSize.height;
		}
		
		return screenH;

	}
	
	function estaEmpresa(indice,empresaTxt){
		for(i=0;i<indice.length;i++){
			if(indice[i]==empresaTxt) return 1;
		}
		return 0;
	}
	
	function deleteCookie (cookieName){	
		document.cookie = cookieName+"=; expires=Thu, 01-Jan-70 00:00:01 GMT;path=/";
	}
	
	function actualizaLastData(paso){	
		if(typeof userLastData == 'string')
			userLastData = new Object();
		
		if(paso ==1){
			if(userLastData.nombres != $F('nombres').trim()) userLastData.nombres = $F('nombres').trim() ;
			if(userLastData.apellidoPaterno != $F('apellidoPaterno').trim()) userLastData.apellidoPaterno = $F('apellidoPaterno').trim();
			var fechaNacto = $('dia').value+"/"+$('mes').value+"/"+$('anno').value;
			if(userLastData.fechaNacimiento != fechaNacto) userLastData.fechaNacimiento = fechaNacto;
			if(userLastData.documentoIdentidad != $F('documentoIdentidad').trim()) userLastData.documentoIdentidad = $F('documentoIdentidad').trim();
			if(userLastData.tipoDocumentoIdentidad != $F('tipoDocumentoIdentidadId').trim()) userLastData.tipoDocumentoIdentidad = $F('tipoDocumentoIdentidadId').trim();
			
			if(userLastData.direccion != $F('calle').trim()) userLastData.direccion = $F('calle').trim();
			if(userLastData.paisId != $('paisResidenciaId').value) userLastData.paisId = $('paisResidenciaId').value;
			if(userLastData.regionId != $('regionId').value)	 userLastData.regionId = $('regionId').value;
			if(userLastData.comunaId != $('comunaId').value)	 userLastData.comunaId = $('comunaId').value;
			if(userLastData.telefonoFijo != $F('telefonoFijo').trim()) userLastData.telefonoFijo = $F('telefonoFijo').trim();
			if(userLastData.telefonoMovil !=$F('telefonoMovil').trim()) userLastData.telefonoMovil = $F('telefonoMovil').trim();
			
			//if( $('rutaCv').innerHTML != "" || $('localFileUpload').value!="" )userLastData.cvFile ="1";
			
			var borrar = document.getElementById("borrarFoto");
			if( borrar.innerHTML != '')	 userLastData.urlFotoPersonal = "1";
		}
		else if(paso == 2){
			 var element = document.getElementById("estudiosTabla");
			 var tablaEstudio = element.firstChild;
			 if(tablaEstudio.firstChild.tagName != "CAPTION"){			
				userLastData.grupoEstudio = "5";
				userLastData.institucion = tablaEstudio.firstChild.firstChild.childNodes[1].innerHTML;
				userLastData.otraInstitucion = tablaEstudio.firstChild.firstChild.childNodes[1].innerHTML;
			
			 }else{
				 userLastData.grupoEstudio = "0";
				 userLastData.institucion = "";
				 userLastData.otraInstitucion ="";
			 }
			 
		}
		else{
			userLastData.aniosExperiencia = $('annosExperiencia').value;
			userLastData.trabajando =$RF('workingId');
			 var element = document.getElementById("experienciasTabla");
			 var tablaExperiencia = element.firstChild;	
			 if(tablaExperiencia.childElementCount >2){
				userLastData.tipoTrabajo = tablaExperiencia.childNodes[2].firstChild.childNodes[0].innerHTML;
				userLastData.nombreCargo = tablaExperiencia.childNodes[2].firstChild.childNodes[1].innerHTML;
				userLastData.empresa = tablaExperiencia.childNodes[2].firstChild.childNodes[2].innerHTML;		
			 }else{
				userLastData.tipoTrabajo ="";
				userLastData.nombreCargo = "";
				userLastData.empresa = "";
			 }
		}
		userLastData.fechaActualizacion = userData.cvfUpdate;
		deleteCookie("LABORUMPOSTULANTE_LASTDATA");		
		document.cookie = "LABORUMPOSTULANTE_LASTDATA="+encodeHTML(Object.toJSON(userLastData))+";path=/"; 
	}
	
	
	
	

	function eliminarAnnosExtra(cantAnos, idSelect){
		var element = document.getElementById(idSelect);
		for(i=0; i<cantAnos; i++){
			element.removeChild(element.firstChild);
		}
	}
	
	
	validaIdentidad = function(val, tipo, docu){ 
	try{ 
		if( $(tipo).value == "1" ){  //RUT soporta solo números
			$(docu).value = formatNumber(val.replace(/[^0-9]/g, ''));
		}else{  //pasaporte soporta números y letras 
			$(docu).value = formatNumber(val.replace(/[^0-9A-Za-z]/g, ''))
		}
	}catch(err){alert(err)}
	}
	
	
	desplegarAnioFin = function(idEstadoEstudio){
		if(idEstadoEstudio=="1" || idEstadoEstudio=="6"){  //egresado o titulado
			if(idEstadoEstudio=="1")  $("spanFinalizacion").innerHTML = "egreso";
			if(idEstadoEstudio=="6")  $("spanFinalizacion").innerHTML = "titulaci&oacute;n";
				
			$("divAnioFinalizacion").style.display = 'block';
		}else{
			$("divAnioFinalizacion").style.display = 'none';
			if($("highSchoolEndYear")!=null) $("highSchoolEndYear").value = "0";
			if($("graduateEndYear")!=null) $("graduateEndYear").value = "0";
		}
	}
	isIndustryRRHH = function(stindusId){
	
		for(var i = 0; i< industryRRHH.length; i++){
			if(stindusId == industryRRHH[i])
				return true;
		}
		return false;
	}


