/*
funciones de javascript para comprobar formularios
creadas por: Duilio Palacios
e-mail: solo@otrotiempo.com
Licencia: CreativeCommons
*/
ie=document.all;

function ajax_cambiar_home(WEB, id) {
	if($('#star'+id).attr('title') == 'si')	tipo = 'no';	else	tipo = 'si';
	url = WEB+'xml/postulados/destacado/'+id+'/'+tipo;
	$.ajax({
	  url: url,
		async: false,
   	complete: cambiar_icono_home
  });
}
function cambiar_icono_home(objXML) {
	xml = objXML.responseXML;
	aItems = xml.getElementsByTagName('item');
  starid = document.getElementById('star'+aItems.item(0).getAttribute('id') );	
	tipo = aItems.item(0).getAttribute('tipo')
	starid.setAttribute('src','css/img/adm/destacado-'+tipo+'.gif');
	starid.setAttribute('title',tipo);
}

function enviarValidacion(formulario)
{

	if( confirm('esta seguro que desea guardar este pago? Esta accion no podra deshacerse.') ) {
		enviar(formulario);
	}
}

function cambiar(nombre, estado) {
	$("#"+nombre).attr("value", estado);
}

function filtrar_busqueda(MOD) {
	mes  = $('#option_meses').val();
	anio = $('#option_anios').val();
	param = obtenerParametros('filtros');
	if( (mes != 0) || (anio != 0) ) {
		if( (anio == 0) || (mes == 0) ) {
			alert("Debe seleccionar tanto el anyo como el mes para filtrar por fecha");
		} else {
			document.location.href = MOD+'lista/'+anio+'/'+mes+param;
		}
	} else {
		document.location.href = MOD+'lista'+param;
	}
}

function eliminar(registro) {
	if ( confirm('Esta seguro de que desea eliminar el registro seleccionado?') ) {
		if ( !ie ) formulario = document.getElementById('formulario');
		formulario.id.value = registro;
		formulario.submit();
	}
}

function validar(formulario,mandar) {
	
	/*uncomment to invalidate for PHP validation testing purposes*/
	/*
	enviar(formulario);
	return;
	*/
	/**/
	
	var borrador = document.getElementById("estado_borrador");
	
	if(borrador && borrador.checked) {
		enviar(formulario);
		return;		
	}

	var listaErrores = document.getElementById("lista_errores");
	limpiarNodo(listaErrores);
	modificado = esModificado();
	var campos  = formulario.getElementsByTagName("input");
	longitud = campos.length;
	for(i=0; i<longitud; i++) {
		var campo = new clsCampo( campos.item(i) );
		if(campo.tipo == false) continue;
		if ( (campo.type == "text") || (campo.type == "hidden") ) {
			if ( !( campo.esObligatorio() && campo.vacio() ) )
			{
				eval("campo."+campo.tipo+"();" );
			}
		} else if ( ( campo.type == "file" ) || ( campo.type == "password" ) ) {
			if(campo.tipo == false) continue;
			if ( !modificado && campo.esObligatorio() )
				campo.vacio();
			  eval("campo."+campo.tipo+"();" );
		}
		if (campo.error)
		  listaErrores.appendChild( crearLI( campo.error ) );
	}
	campos = formulario.getElementsByTagName("textarea");
	longitud = campos.length;
	for (i=0; i<longitud; i++) {
		var campo = new clsCampo( campos.item(i) );
		if(campo.tipo == false) continue;
		if ( campo.esObligatorio() && campo.vacio() )
		  listaErrores.appendChild( crearLI( campo.error ) );
	}
	campos = formulario.getElementsByTagName("select");
	longitud = campos.length;
	for (i=0; i<longitud; i++) {
		var campo = new clsCampo( campos.item(i) );
		if(campo.tipo == false) continue;
		if(campo.esObligatorio() && !campo.combo() )
		  listaErrores.appendChild( crearLI( campo.error ) );
	}
	formValido = !listaErrores.getElementsByTagName("li").length;
	if (!formValido) window.scroll(0,0);
	if (formValido && mandar) enviar(formulario);
	return formValido;

}
/***/
function clsCampo (campo) {
	this.campo = campo;
	this.type = this.campo.getAttribute("type");
	if(camposValidos[this.campo.name] != undefined)
		this.tipo = camposValidos[this.campo.name].toLowerCase();
	else
		this.tipo = false;
	if( (this.type != "file" ) && (this.tipo != 'editor' ) )
	  this.campo.value = trim(this.campo.value);
	this.error = false;
}
clsCampo.prototype.esObligatorio = function esObligatorio() {
	var chr = camposValidos[this.campo.name].charAt(0);
	if ( chr.search('[A-Z]') || (chr == 'W') ) return false;
	return true;
}
clsCampo.prototype.vacio = function vacio() {
	valor = trim(this.campo.value);
	if ( valor.length!=0 ) return false;
	this.error = 'Debe completar el campo "'+this.formatoNombre()+'"';
	return true;
}
clsCampo.prototype.alpha = function alpha() {
	return true;
}
clsCampo.prototype.radio = function radio() {
	n = this.campo.length;
	for(i=0;i<n;i++)
		if(this.campo[i].checked) return true;
	this.error = 'Debe marcar un "'+this.formatoNombre()+'"';
	return false;
}
clsCampo.prototype.usuario = function usuario() {
	return true;
}
clsCampo.prototype.natural = function natural() {
	if ( this.campo.value.search('[^0-9]') == -1 ) return true;
	this.error = 'el campo "'+this.formatoNombre()+'" solo puede tener numeros enteros sin signo';
	return false;
}
clsCampo.prototype.entero = function entero() {
	if ( this.campo.value.search('^-?[0-9]+$') != -1 ) return true;
	this.error = 'el campo "'+this.formatoNombre()+'" solo puede tener numeros enteros';
	return false;
}
clsCampo.prototype.real_positivo = function real_positivo() {
	if ( this.campo.value.search('[^0-9.]') == -1 ) return true;
	this.error = 'el campo "'+this.formatoNombre()+'" solo puede tener numeros sin signo';					 
	return false;
}
clsCampo.prototype.real = function real() {
	if ( this.campo.value.search('[^0-9.-]') == -1 ) return true;
	this.error = 'el campo "'+this.formatoNombre()+'" solo puede tener numeros';
	return false;
}
clsCampo.prototype.texto = function texto() {
	if ( this.campo.value.search('^[a-z A-Z]+$') != -1 ) return true;
	this.error = 'el campo "'+this.formatoNombre()+'" solo puede tener texto';
	return false;
}
clsCampo.prototype.correo = function correo() {
	valor = trim(this.campo.value);
	if(valor.length == 0) return true;
	this.campo.value = this.campo.value.toLowerCase();
	if ( this.campo.value.search('^[a-z][a-z0-9\-_.]+[@][a-z0-9\-_.]+[.][a-z]{2,3}$') != -1 ) return true;
	this.error = 'el campo "'+this.formatoNombre()+'" debe ser un correo valido';
	return false;
}
clsCampo.prototype.url = function url() {
	valor = trim(this.campo.value);
	if(valor.length == 0) return true;
	this.campo.value = valor.toLowerCase();
	if ( this.campo.value.search('^[^@]+[.][a-z]{2,3}$') != -1 ) {
		if ( this.campo.value.search('^http://') == -1 ) this.campo.value = 'http://'+this.campo.value;
		return true;
	}
	this.error = 'el campo "'+this.formatoNombre()+'" debe ser una URL valida';
	return false;
}
clsCampo.prototype.contrasena = function contrasena() {
	
	campo = this.formatoNombre();
	
	campo2 = document.getElementById(this.campo.name.substr(0)+'_confirmar');
	
	if ( (this.campo.value=="") && (campo2.value=="") ) return true;
	
	if ( this.campo.value.length < 4 ) {
	  this.error = 'El campo "'+campo+'" debe tener minimo cuatro (4) caracteres';
	  return false;
	}
	
	if ( this.campo.value == campo2.value ) return true;
	  
	this.campo.value = "";
	campo2.value = "";
	
	this.error = 'Los campos "'+campo+'" y "Confirmar '+campo+'" deben coincidir."';
	return false;
}
clsCampo.prototype.archivo = function archivo() {
	return true;
}
clsCampo.prototype.combo = function combo() {
	var valor = parseInt(this.campo.selectedIndex);
	if ( !isNaN(valor) && valor ) return true;
	this.error =  'Debe seleccionar un valor del combo "'+this.formatoNombre()+'"';
	return false;
}
/***/
clsCampo.prototype.formatoNombre = function formatoNombre() {
	nombre = this.campo.name;
	if(nombre.indexOf('id_') === 0)
		nombre = nombre.charAt(3).toUpperCase()+nombre.replace(/_/g,' ').substr(4);
	else if(nombre.indexOf('img_') === 0)
		nombre = nombre.charAt(4).toUpperCase()+nombre.replace(/_/g,' ').substr(5);
	else
		nombre = nombre.charAt(0).toUpperCase()+nombre.replace(/_/g,' ').substr(1);
	if(nombre.indexOf('[') == -1)
		return nombre;
	else
		return nombre.replace(/\[(.*)\]/g,' ($1)');
}
function enviar(formulario) {
	formulario.boton.setAttribute('disabled','disabled');
	formulario.submit();
}
function esModificado() {
	if ( parseInt( document.getElementById('id').value ) ) return true;
	else return false;
}
function trim(str) {
	return str.replace(/^\s*|\s*$/g,"");
}
/* DOM */
function crearLI(txt){
	var objLI = document.createElement('li');
	objLI.appendChild( document.createTextNode( txt ) );
	return objLI;
}
function limpiarNodo(nodo){
	while( nodo.hasChildNodes() ) nodo.removeChild(nodo.firstChild);
}