function validaRut(objRut)
{
	var tmpstr = "";
	var intlargo = objRut;
	if (intlargo.length> 0)
	{
		crut = objRut;
		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;
		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 false;
	
		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())
		{
			return false;
		}
		return true;
	}
}

function insertTag(which, tagStart, tagEnd) {
    myField = document.getElementById(which);
	//IE support
	if (document.selection) {
		myField.focus();
	    sel = document.selection.createRange();
		if (sel.text.length > 0) {
			sel.text = tagStart + sel.text + tagEnd;
		}
		else {
			sel.text = tagStart + tagEnd;
			sel.moveStart('character',-tagEnd.length);
			sel.moveEnd('character', -tagEnd.length); 
			sel.select();
		}
		myField.focus();
	}
	//MOZILLA/NETSCAPE support
	else if (myField.selectionStart || myField.selectionStart == '0') {		
		var startPos = myField.selectionStart;
		var endPos = myField.selectionEnd;
		var cursorPos = endPos;
		var scrollTop = myField.scrollTop;
		if (startPos != endPos) {
			myField.value = myField.value.substring(0, startPos)
			              + tagStart
			              + myField.value.substring(startPos, endPos) 
			              + tagEnd
			              + myField.value.substring(endPos, myField.value.length);
			cursorPos += tagStart.length + tagEnd.length;
		}
		else {
			myField.value = myField.value.substring(0, startPos) 
				              + tagStart + tagEnd
				              + myField.value.substring(endPos, myField.value.length);
			cursorPos = startPos + tagStart.length;
		}
		myField.focus();
		myField.selectionStart = cursorPos;
		myField.selectionEnd = cursorPos;
		myField.scrollTop = scrollTop;
	}
}

function btnOnMouseOver(boton)
{
	boton.style.cursor = "pointer";
	boton.src = "img/" + boton.id + "_on.gif";	
}

function btnOnMouseOut(boton)
{
	boton.style.cursor = "default";
	boton.src = "img/" + boton.id + ".gif";
}

function submenuMouseClick(name)
{
	switch(name)
	{
		case 'empresa':
			url = 'empresa/index.asp';
			updateDiv('div_contenido', url);
			break;
		case 'mision':
			url = 'empresa/mision.asp';
			updateDiv('div_contenido', url);
			break;
		case 'vision':
			url = 'empresa/vision.asp';
			updateDiv('div_contenido', url);
			break;
		case 'certificaciones':
			url = 'empresa/certificaciones.asp';
			updateDiv('div_contenido', url);
			break;		
		case 'mineria':
			url = 'servicios/mineria.asp';
			updateDiv('div_contenido', url);
			break;
		case 'transporte':
			url = 'servicios/transporte.asp';
			updateDiv('div_contenido', url);
			break;
		case 'complementarios':
			url = 'servicios/complementarios.asp';
			updateDiv('div_contenido', url);
			break;
		case 'equipos':
			url = 'venta/equipos.asp';
			updateDiv('div_contenido', url);
			break;			
		case 'clientes':
			url = 'venta/clientes.asp';
			updateDiv('div_contenido', url);
			break;			
		case 'trabajo':
			url = 'trabajo/trabajo.asp';
			updateDiv('div_contenido', url);		
			break;
		case 'ofertas':
			url = 'trabajo/ofertas.asp';
			updateDiv('div_contenido', url);		
			break;
		case 'foro':
			url = 'foro/listado.asp';
			updateDiv('div_contenido', url);						
			break;			
	}
}

function goPage(name)
{
	updateDiv('div_menu', 'lib/menu.asp', 'active='+name);
	updateDiv('div_submenu', 'lib/submenu.asp', 'active='+name);

	switch(name)
	{
		case 'empresa':
			url = 'empresa/index.asp';
			updateDiv('div_contenido', url);
			break;
		case 'servicios':
			url = 'servicios/transporte.asp';
			updateDiv('div_contenido', url);		
			break;
		case 'politica':
			url = 'politica/index.asp';
			updateDiv('div_contenido', url);		
			break;
		case 'venta':
			url = 'venta/equipos.asp';
			updateDiv('div_contenido', url);				
			break;
		case 'trabajo':
			url = 'trabajo/trabajo.asp';
			updateDiv('div_contenido', url);		
			break;
		case 'foro':
			url = 'foro/listado.asp';
			updateDiv('div_contenido', url);						
			break;				
		case 'contacto':
			url = 'contacto/index.asp';
			updateDiv('div_contenido', url);						
			break;
		case 'login':
			url = 'login/index.asp';
			updateDiv('div_contenido', url);						
			break;			
	}
}

function verNoticia(noticia)
{
	var noticia = noticia || '';
	goPage('noticia');
	
	if(noticia!="")
	{
		url = 'noticias/noticia.asp';
		updateDiv('div_contenido', url, "noticia="+noticia);		
	}
	else
	{
		url = 'noticias/index.asp';
		updateDiv('div_contenido', url);
	}	
}

function updateDiv(name, url, param)
{
	var param = param || '';
	new Ajax.Updater($(name), url, {method: 'POST', postBody: param, evalScripts: true});
}

function mensaje(response)
{
	alert(response.responseText);
}

function MM_preloadImages() { //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];}}
}

function validarFormAgregarCurriculum()
{
	// valida el campo
	var nombre = new LiveValidation('txt_nombre', {onlyOnSubmit: true} );
	nombre.add(Validate.Presence, {failureMessage: "Este campo no debe ser vacío"} );
	
	// valida el campo
	var cedula = new LiveValidation('txt_cedula', {onlyOnSubmit: true} );
	cedula.add(Validate.Presence, {failureMessage: " "} );
	cedula.add(Validate.Numericality, {onlyInteger: true, notANumberMessage: "Ingrese sólo números", notAnIntegerMessage: "Ingrese un número entero"} );
	
	// valida el campo
	var verificador = new LiveValidation('txt_digitov', {onlyOnSubmit: true} );
	verificador.add(Validate.Presence, {failureMessage: "Este campo no debe ser vacío"} );
	verificador.add(Validate.Format, {pattern: /(([0-9])|(K))$/i , failureMessage: "Número de cédula incorrecta."} );
	
	// valida el campo
	var email = new LiveValidation('txt_email', {onlyOnSubmit: true });
	email.add(Validate.Presence, {failureMessage: "Este campo no debe ser vacío" } );
	email.add(Validate.Email, {failureMessage: "Ingrese un email valido." });		

	// valida el campo
	var ciudad = new LiveValidation('txt_ciudad', {onlyOnSubmit: true });
	ciudad.add(Validate.Presence, {failureMessage: "Este campo no debe ser vacío" } );
	
	// valida el campo
	var telefono = new LiveValidation('txt_telefono', {onlyOnSubmit: true });
	telefono.add(Validate.Presence, {failureMessage: "Este campo no debe ser vacío" } );
	telefono.add(Validate.Format, { pattern: /^(^(([0-9]+)[-| ]?)+)([0-9]+)$/i , failureMessage: "Utilice solo números y guiones" });	
	
	// valida el campo
	var nacimiento = new LiveValidation('txt_nacimiento', {onlyOnSubmit: true });
	nacimiento.add(Validate.Presence, {failureMessage: "Este campo no debe ser vacío" } );
	nacimiento.add(Validate.DateFormat, {failureMessage: "Ingrese una fecha válida" });

	// valida el campo
	var institucion = new LiveValidation('txt_institucion', {onlyOnSubmit: true });
	institucion.add(Validate.Presence, {failureMessage: "Este campo no debe ser vacío" } );
	
	// valida el campo
	//var especialidad = new LiveValidation('txt_especialidad', {onlyOnSubmit: true });
	//especialidad.add(Validate.Presence, {failureMessage: "Este campo no debe ser vacío" } );	
	
	// valida el campo
	var egreso = new LiveValidation('txt_egreso', {onlyOnSubmit: true });
	egreso.add(Validate.Presence, { failureMessage: "Este campo no debe ser vacío"});
	egreso.add(Validate.Numericality, {onlyInteger: true, notANumberMessage: "Ingrese sólo números", notAnIntegerMessage: "Ingrese un número entero", tooLowMessage: "Ingrese un año mayor a 1900", minimum:1900 });	
	
	// valida el campo
	var experiencia = new LiveValidation('txt_experiencia', {onlyOnSubmit: true });
	experiencia.add(Validate.Presence, { failureMessage: "Este campo no debe ser vacío"});
	experiencia.add(Validate.Numericality, {onlyInteger: true, notANumberMessage: "Ingrese sólo números", notAnIntegerMessage: "Ingrese un número positivo entre (0-99)", tooLowMessage: "Ingrese un número positivo entre (0-99)", tooHighMessage: "Ingrese un número positivo entre (0-99)", minimum:0 });

	// valida el campo
	var pretensiones = new LiveValidation('txt_pretensiones', {onlyOnSubmit: true });
	pretensiones.add(Validate.Numericality, {onlyInteger: true, notANumberMessage: "Ingrese sólo números", notAnIntegerMessage: "Ingrese un número entero"});	
		
	// validate the file format doc
	var cv = new LiveValidation('txt_cv', {onlyOnSubmit: true });
	cv.add(Validate.Format, { pattern: /((doc)|(pdf))$/i , failureMessage: "(DOC-PDF)" });	
	
	var automaticOnSubmit = nombre.form.onsubmit;
	nombre.form.onsubmit = function()
	{
		var valid = automaticOnSubmit();
		if(valid)
		{
			var rut = $F("txt_cedula") + "-" + $F("txt_digitov");
			if(!validaRut(rut))
			{
				alert("El RUT Ingresado no es válido.");
				$("txt_cedula").focus();
				return false;
			}
			$("txt_estudios").value = $("cbx_estudios").options[$("cbx_estudios").selectedIndex].text;
			activarCargaDatos();
			return true;	
		}
		return false;
	}	
}

function showSaveCurriculum(response)
{
	desactivarCargaDatos();
	var rjson = eval("("+ response + ")");
	if(rjson.error==0)
	{
		alert(rjson.mensaje);
	}
	else
		alert(rjson.mensaje);
}

function validarFormPostularTrabajo()
{
	// valida el campo
	var cedula = new LiveValidation('txt_cedula', {onlyOnSubmit: true} );
	cedula.add(Validate.Presence, {failureMessage: " "} );
	cedula.add(Validate.Numericality, {onlyInteger: true, notANumberMessage: "Ingrese sólo números", notAnIntegerMessage: "Ingrese un número entero"} );	
	
	// valida el campo
	var verificador = new LiveValidation('txt_digitov', {onlyOnSubmit: true} );
	verificador.add(Validate.Presence, {failureMessage: "Este campo no debe ser vacío"} );
	verificador.add(Validate.Format, {pattern: /(([0-9])|(K))$/i , failureMessage: "Número de cédula incorrecta."} );
	
	var automaticOnSubmit = cedula.form.onsubmit;
	cedula.form.onsubmit = function()
	{
		var valid = automaticOnSubmit();
		if(valid)
		{
			activarCargaDatos();			
			pParam = "oferta=" + $F("oferta") + "&cedula=" + $F("txt_cedula") + "-" + $F("txt_digitov");
			// save data function
			new Ajax.Request('trabajo/postulacion.asp',{
				method: 'POST',
				postBody: pParam,
				onSuccess: showSavePostularTrabajo,
				onFailure: showErrorConexion
			});			
		}
		return false;
	}	
}

function showSavePostularTrabajo(response)
{
	desactivarCargaDatos();
	var rjson = eval("("+ response.responseText + ")");
	if(rjson.error==0)
	{
		alert(rjson.mensaje);
	}
	else
		alert(rjson.mensaje);
		
	submenuMouseClick('ofertas');
}

function validarFormAgregarTema()
{
	// valida el campo
	var nombre = new LiveValidation('txt_nombre', {onlyOnSubmit: true} );
	nombre.add(Validate.Presence, {failureMessage: "Este campo no debe ser vacío"} );	
	
	// valida el campo
	var email = new LiveValidation('txt_email', {onlyOnSubmit: true });
	email.add(Validate.Presence, {failureMessage: "Este campo no debe ser vacío" } );
	email.add(Validate.Email, {failureMessage: "Ingrese un email valido." });		

	// valida el campo
	var titulo = new LiveValidation('txt_titulo', {onlyOnSubmit: true} );
	titulo.add(Validate.Presence, {failureMessage: "Este campo no debe ser vacío"} );	

	// valida el campo
	var descripcion = new LiveValidation('txt_descripcion', {onlyOnSubmit: true} );
	descripcion.add(Validate.Presence, {failureMessage: "Este campo no debe ser vacío"} );			
	
	var automaticOnSubmit = nombre.form.onsubmit;
	nombre.form.onsubmit = function()
	{
		var valid = automaticOnSubmit();
		if(valid)
		{
			activarCargaDatos();
			return true;	
		}
		return false;
	}	
}

function showSaveTema(response)
{
	desactivarCargaDatos();
	var rjson = eval("("+ response + ")");
	if(rjson.error==0)
	{
		alert(rjson.mensaje);
		submenuMouseClick('foro');
	}
	else
		alert(rjson.mensaje);
}

function validarFormAgregarComentario()
{
	// valida el campo
	var nombre = new LiveValidation('txt_nombre', {onlyOnSubmit: true} );
	nombre.add(Validate.Presence, {failureMessage: "Este campo no debe ser vacío"} );	
	
	// valida el campo
	var email = new LiveValidation('txt_email', {onlyOnSubmit: true });
	email.add(Validate.Presence, {failureMessage: "Este campo no debe ser vacío" } );
	email.add(Validate.Email, {failureMessage: "Ingrese un email valido." });		

	// valida el campo
	var descripcion = new LiveValidation('txt_descripcion', {onlyOnSubmit: true} );
	descripcion.add(Validate.Presence, {failureMessage: "Este campo no debe ser vacío"} );			
	
	var automaticOnSubmit = nombre.form.onsubmit;
	nombre.form.onsubmit = function()
	{
		var valid = automaticOnSubmit();
		if(valid)
		{
			activarCargaDatos();
			return true;	
		}
		return false;
	}	
}

function showSaveComentario(response)
{
	desactivarCargaDatos();
	var rjson = eval("("+ response + ")");
	if(rjson.error==0)
	{
		alert(rjson.mensaje);
		submenuMouseClick('foro');
	}
	else
		alert(rjson.mensaje);
}

function activarCargaDatos()
{
	$("btn_agregar").disabled = true;
	$("div_loading").innerHTML = '<img src="img/ajax-loader.gif" width="31" height="31" /> Espere mientras se procesa su petici&oacute;n..';
}

function desactivarCargaDatos()
{
	if($("div_loading"))
	{
		$("div_loading").innerHTML = '';
	}
	$("btn_agregar").disabled = false;
}

function showErrorConexion()
{
	alert("No se pudo establecer la conexión con la página solicitada.");
	desactivarCargaDatos();
}

function login()
{
	// validate the state name field
	var username = new LiveValidation('txt_username', {onlyOnSubmit: true });
	username.add(Validate.Presence, {failureMessage: "Complete el username"});

	// validate the state name field
	var password = new LiveValidation('txt_password', {onlyOnSubmit: true });
	password.add(Validate.Presence, {failureMessage: "Complete el password"});
	
	var automaticOnSubmit = username.form.onsubmit;
	username.form.onsubmit = function()
	{
		var valid;
		try
		{		
			valid = automaticOnSubmit();
			if(valid)
			{
				param = "txt_username=" + $F("txt_username") + "&txt_key=" + hex_sha1($F('txt_password').toLowerCase());
					
				new Ajax.Request('login/login.asp',{
					method: 'POST',
					postBody: param,
					onSuccess: loginAccess,
					onFailure: showErrorConexion
				});
			}
			return false;
		}
		catch(err)
		{		
			alert(err.toString() + "\n" + err.description);
			return false;
		}		
	}	
}

function loginAccess(response)
{
	var rjson = eval("("+ response.responseText + ")");
	if(rjson.error==0)
	{
		window.location = rjson.url;
	}
	else
		alert(rjson.mensaje);	
}
