var emailtype =/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;

var url = "/appjob/jobs";
var characterEncoding="UTF-8";

function validaFormularioPersona(){
	msg = "";
	if (validaRut($('rut').value)==false)
		msg+='- El Rut es inv\u00e1lido\n';
	if ($('nombres').value==0)
		msg+='- Debe ingresar sus nombres\n';
	if ($('apellidoP').value==0)
		msg+='- Debe ingresar su primer apellido\n';
	if ($('celular').value==0 &&  ( $('telefono').value==0 || $('codigo').value==0))		
		msg+='- Debe ingresar un celular o un tel\u00e9fono fijo (con c\u00f3digo)\n';
	
	if($('contrasena').value != $('contrasena2').value || ($('contrasena').value.length<6)){
		msg+='- Las contrase\u00f1as no coinciden o son muy cortas (6 carac. m\u00ednimos)\n';
	}	
	if ($('regionTrabajoId').value==-1)
		msg+='- Debe seleccionar regi\u00f3n de residencia\n';
	
	if ($('comunaId').value==-1 || $('comunaId').value==-0)
		msg+='- Debe seleccionar comuna\n';
	
	
	
	if (msg.length>0){
		alert('El usuario no puede ser creado, debido a que se encontraron\nlos siguientes problemas:\n'+msg);
		return false;
	}
	else return true;
	
}

function validaLogin(){
	msg = "";
	if (validaRut($('rut').value)==false)
		msg+='- El Rut es inv\u00e1lido\n';
	if($('contrasena').value.length<6){
		msg+='- Las contrase\u00f1a es muy corta (6 carac. m\u00ednimos)\n';
	}	
	if (msg.length>0){
		alert('Existen los siguientes problemas para iniciar sesi\u00f3n:\n'+msg);
		return false;
	}
	else return true;
}

function nuevoUsuario (){
	
	if(!validaFormularioPersona())
		return false;
	
	var sexo;

	
	sexo = $('sexo').value;	
	
	var pars = "action=LALONuevoUsuario"+
	"&nombre="+$('nombres').value+
	"&apellidoM="+$('apellidoM').value+
	"&apellidoP="+$('apellidoP').value+
	"&rut="+$('rut').value.replace(".","").replace(".","").replace("-","")+
	"&region="+$('regionTrabajoId').value+
	"&comuna="+$('comunaId').value+
	"&mail="+$('mail').value+
	"&comentario=comentario"+
	"&sexo="+sexo+
	"&celular="+$('celular').value+
	"&telefono=("+$('codigo').value+")"+$('telefono').value+
	"&fax=("+$('codigo').value+")"+$('fax').value+
	"&contrasena="+$('contrasena').value;
	
    new Ajax.Request(
		url,
		{
		method:"post",
		parameters: pars,
		encoding: characterEncoding,
		onSuccess : function (resp){ 
			var data = resp.responseJSON || "no response text";
			if (data.exito!=undefined && data.exito=="true"){
				alert(data.msg);
				location.href='index.html';
			}
			else
				alert(data.msg);
		}
		}
	)
}

function  buscarOferta(){
	var tipo=-1;
	if($('ofrece').checked)
		tipo = $('ofrece').value;
	
	if($('busca').checked)
		tipo = $('busca').value;
	
	if($('todoOfertas').checked)
		tipo = $('todoOfertas').value;
	
	var pars = "action=LALOBuscar"+
	"&palabra="+$('palabra').value+
	"&area="+$('area').value+
	"&region="+$('region').value+
	"&tipo="+tipo;
	
    new Ajax.Request(
		url,
		{
		method:"post",
		parameters: pars,
		encoding: characterEncoding,
		asynchronous:false,
		onSuccess : desplegarOfertas
		}
	)
}

function desplegarOfertas(resp){
	var data = resp.responseJSON || "no response text";
	var listadoAvisos=""
	if (data.length>0){
		for (i=0;i<data.length;i++){
			datoOferta = data[i];
			listadoAvisos+=ofertaRecientes(0,datoOferta.titulo,datoOferta.fecha,datoOferta.descripcion,datoOferta.web, datoOferta.contactoCelular, datoOferta.contactoMail, datoOferta.contactoFono, datoOferta.contactoComentario, datoOferta.contactoNombre, datoOferta.regiones, datoOferta.comunas, i);
			
		}
	}else{
		listadoAvisos='<b>Su b&uacute;squeda no obtuvo ning&uacute;n resultado.</b>'
	}
	$('titCabOfertas').innerHTML = "<h2>Listado de ofertas</h2></div>";      
	$('contenidoOfertas').innerHTML = listadoAvisos;
	
	
}


function salir(){
	var pars = "action=LALOFinSesion";
	 new Ajax.Request(
				url,
				{
				method:"post",
				parameters: pars,
				encoding: characterEncoding,
				onSuccess : function (){location.href='index.html';}
				}
			)
}



function crearNuevoAviso(nuevo){
	//nuevo indica si se esta intentando enviar al servidor

	if (nuevo=="false"){
		var cookieValida = validaCookie();
		if (cookieValida==false){
			if(confirm ("Para crear nuevos avisos hay que estar registrado en el sitio. \u00BFDesea registrarse ahora\u003F"))
				location.href='login.html';
			else
				location.href='index.html';
		}
		else 
			location.href='crearAviso.html';
	}
	else{
		var cookieValida = validaCookie();
		if (cookieValida==false){
			if(confirm ("Para crear nuevos avisos hay que estar registrado en el sitio. \u00BFDesea registrarse ahora\u003F"))
				location.href='login.html';
			else
				location.href='index.html';
		}
	}
}
function validaCookie(){
	
	var NOMBRE_COOKIE = "LABORUMALAOBRA";
	var a_all_cookies = document.cookie.split( ';' );
	
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for (var i = 0; i < a_all_cookies.length; i++ )
	{
		
		a_temp_cookie = a_all_cookies[i].split( '=' );
		if (a_temp_cookie.length>1){
			cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
			var asd = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			if ( cookie_name == NOMBRE_COOKIE){
				var CookieDecode= utf8_decode(asd);
				respuesta = CookieDecode.evalJSON() || "no response text";
				var nombre = respuesta.nombre +" "+ respuesta.apellidoP;
				$("nuevoUsuarioORegistrado").innerHTML = "Bienvenido <strong>"+nombre+"</strong>";				
				$("registrarse").style.display="none";
				$("salir").style.display="block";
				b_cookie_found=true
				
				$("nameUser").innerHTML = "Bienvenido <strong>"+nombre+"</strong>";
				$('userLogin').style.display="none";
			}
		}
	}
	
	return b_cookie_found;
}

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;
    }

function inicioSesion(){
	if (validaLogin()==false)
		return false;
	var pars = "action=LALOLogin"+
	"&rut="+$('rut').value.replace(".","").replace(".","").replace("-","")+
	"&contrasena="+$('contrasena').value;

    new Ajax.Request(
		url,
		{
		method:"post",
		parameters: pars,
		
		encoding: characterEncoding,
		asynchronous:false,
		onSuccess : function (resp){
			var data = resp.responseJSON || "no response text";
			if(data.exito=="true"){
				location.href='index.html';
				
			}
			else{
				alert("El RUT y la contrase\u00f1a no coinciden, por favor vuelva a intentarlo");
				$('contrasena').innerHTML = "";
			}
		}
		
		}
	)
}

changeOptionP = function(id,divId,typeOption,optionId,onChange)	{
	var element = document.getElementById(divId);
  	while (element.firstChild) element.removeChild(element.firstChild);

		new Ajax.Request
		("/ajax.data/"+typeOption+"/"+id+".html",
			{
			method:'POST',encoding: characterEncoding,asynchronous:false,
			onSuccess : function(resp) {
										var textReturn = resp.responseText || "no response text";
										if (typeOption=='comunas'){
										$(divId).innerHTML="<select class='insel' name="+optionId+" style='width: 235px' id="+optionId+" onChange="+onChange+">"+
															"<option value='0'>Selecciona</option>"+
															"<option value='-1'>Todas</option>"+
															"<optgroup label='-------------------------'></optgroup>"+
															textReturn+"<\/select>";
										}
										else
											document.getElementById(divId).innerHTML="<select class='insel' name="+optionId+" id="+optionId+" onChange="+onChange+">"+textReturn+"<\/select>";
										}
			}
		);
}

nuevoAviso = function(){
	var residencia_comuna 	= 	valueFilter('filtroComunas');
	var residencia_region 	= 	valueFilter('filtroRegiones');
	var titulo = $('titulo').value;
	var descripcion = $('descripcionAvisoId').value;
	var web = $('web').value;
	var areaTrabajo = $('areaTrabajoId').value;
	var trabajo = $('trabajoId').value;
	
	var msg="";
	 
	
	if(titulo==undefined || titulo.length==0){
		msg+='- T\u0069tulo de la oferta no puede ir en blanco\n';
	}

	if(descripcion==undefined || descripcion.length==0 || descripcion.length>300){
		msg+='- Descripci\u006Fn de la oferta se encuentra en blanco o tiene mas de 300 letras\n';
	}

	if(areaTrabajo<-1 || areaTrabajo==0){
		msg+='- Debe indicar el area de trabajo\n';
	}

	if(trabajo<-1 || trabajo==0){
		msg+='- Debe indicar la profesi\u006Fn\n';
	}
	
	
	
	if (residencia_comuna.length == 0 && residencia_region.length==0)
		msg+='- Debe indicar comuna y/o regi\u006Fn\n';
	

	if(msg.length>0){
		 alert('El aviso no puede ser creado, debido a que se encontraron\nlos siguientes problemas:\n'+msg);
		 return false;
	}
	var tipo = radiobtn;
	var pars = 	"action=LALONuevaOferta" +
				"&titulo="	+titulo+
				"&descripcion="	+descripcion+
				"&web="		+web+
				"&tipo="	+tipo+
				"&area="	+areaTrabajo+
				"&profesion="+trabajo+
				"&regiones="+residencia_region+
				"&comunas="	+residencia_comuna;
	
	
				new Ajax.Request(
						url,
						{
							method:'POST',
							parameters: pars,
							encoding: characterEncoding,
							onSuccess : function(resp){
								var data = resp.responseJSON || "no response text";
								if (data.msg!=undefined)
									alert(data.msg);
								if (data.exito!=undefined && data.exito=="true")
									location.href='index.html';
						}
						}
					);
}


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 radiobtn=1;
function check_radio(este){
	radiobtn = este;
}

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 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
}

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;
      }
    }

    
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 doneRecuperarClave(resp)
{
    var data = resp.responseJSON || "no response text";
	if (data.bError == 0) {
		alert(""+data.mensajeEmailRecuperarClave);
		return false;
	}else{
		alert(""+data.errorEmailRecuperarClave);
		return false;
	}
}

recuperarClave=function recuperarClave() {
	var email=prompt('Ingrese su email');
	if(email.length==0){
		alert("* Necesitamos que ingreses un correo");
		return false;
	}else if (!isValidEmail(email)){
		alert("* Tu correo esta mal escrito");
		return false;
	}

	var url = '/appjob/jobs';

    var pars = ('action=LALORecuperarClave&email='+email);
    new Ajax.Request(
	url,
	{
		method:'POST',
		parameters: pars,
		encoding: characterEncoding,
		onSuccess : doneRecuperarClave

	}
);

}


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;
	}


var ofertaRecientes=function( id,titulo,fecha,desc,web, contactoCelular, contactoMail, contactoFono, contactoComentario, contactoNombre, region, comuna, indice){
	var txtRegionComuna="";
	var txt=region+" - "+comuna;
	
	txtRegionComuna = txt.length>0?txt.substring(0,350)+"...":txt;
	
	
	
	var htmlOferta = "";
		htmlOferta = ""+
		" <div class=\"oferta\"> "+
		" <h3>"+titulo+"<\/a><\/h3> "+
		desc+
		" <p>"+txtRegionComuna+"</p><span class='fecha'>Fecha Publicaci&oacute;n:  "+fecha+"</span> "+
		" <ul> "+
		" <li class=\"contacto\">Nombre:"+contactoNombre+"<\/li> "+
		" <li class=\"contacto\">Web:"+web+"<\/li> "+
		" <li class=\"contacto\">Celular:"+contactoCelular+"<\/li> "+
		" <li class=\"contacto\">Mail:"+contactoMail+"<\/li> "+
		" <li class=\"contacto\">Fono:"+contactoFono+"<\/li> "+
		" <\/ul> "+
		
		" <\/div> "+
		"";

	return htmlOferta;
}


