// validacion de controles
function f_validarFormError() {
	var clase = 'form-error';
	var elementos = $$('*.' + clase);
	if(elementos.length > 0) {
		for(var i=0; i < elementos.length; i++) {
			if(elementos[i].className.search(/form-error/i) >= 0) {
				elementos[i].removeClassName('form-error');
			}
		}
	}
}

function f_validarCampo(control, msg) {
	f_validarFormError();
	if(control == null) {
		alert('Control: No existe.\nMensaje: ' + msg);
		return false;
	}
	if(control.value == '') {
		control.addClassName('form-error');
		alert(msg);
		control.focus();
		return false;
	} else {
		if(control.className.search(/form-error/i) >= 0) {
			control.removeClassName('form-error');
		}
	}
	return true;
}

function f_validarSelect(control, msg) {
	f_validarFormError();
	if(control == null) {
		alert('Control: No existe.\nMensaje: ' + msg);
		return false;
	}
	if(control.selectedIndex == 0) {
		control.addClassName('form-error');
		alert(msg);
		control.focus();
		return false;
	} else {
		if(control.className.search(/form-error/i) >= 0) {
			control.removeClassName('form-error');
		}
	}
	return true;
}

function f_validarSelectMultiple(control, msg) {
	f_validarFormError();
	if(control == null) {
		alert('Control: No existe.\nMensaje: ' + msg);
		return false;
	}
	var exito = true;
	for(var i = 0; i < control.options.length; i++) {
		if(control.options[i].selected === true) {
			exito = true;
			break;
		} else {
			exito = false;
		}
	}
	if(!exito) {
		control.addClassName('form-error');
		alert(msg);
		control.focus();
		return false;
	} else {
		if(control.className.search(/form-error/i) >= 0) {
			control.removeClassName('form-error');
		}
	}
	return true;
}

// validacion por className
function f_validarCampoPorClase(clase, msg) {
	var elementos = $$('input.' + clase);
	if(elementos.length > 0) {
		var vacios = 0;
		for(var i=0; i < elementos.length; i++) {
			if(elementos[i].value == '') {
				vacios++;
			}
		}
		if(vacios > 0) {
			alert(msg);
			elementos[0].focus();
			return false;
		}
	}
	return true;
}

function validarCheckboxUnicoPorClase(clase, msg) {
	var valida = false;
	var elementos = $$('input.' + clase);
	for(var i=0; i < elementos.length; i++) {
		valida = valida || elementos[i].checked;
	}
	if(!valida) {
		alert(msg);
		elementos[0].focus();
	}
	return valida;
}

function validarRadioPorClase(clase, msg) {
	var valida = false;
	var elementos = $$('input.' + clase);
	for(var i=0; i < elementos.length; i++) {
		valida = valida || elementos[i].checked;
	}
	if(!valida) {
		alert(msg);
		elementos[0].focus();
	}
	return valida;
}

// validacion de contenido
function f_validarlongitudMaxima(control, max, msj){
	if(control == null) {
		alert('Control: No existe.\nMensaje: ' + msg);
		return false;
	}
    var valor = eval(control).value;
    if (valor.length > max){
        alert("Caracteres como maximo: " + max + " (" + msj + ")");
        eval(control).value = valor.substring(0, max);
		control.focus();
    	return false;
    }
	return true;
}

function f_validarLongitudMinima(control, min, msj) {
	if(control == null) {
		alert('Control: No existe.\nMensaje: ' + msg);
		return false;
	}
    var valor = control.value;
	if(valor.length < min) {
        alert("Caracteres como minimo: " + min + " (" + msj + ")");
		control.focus();
		return false;
	}
	return  true;
}

function f_validarIgualdad(control1, control2, msg) {
	if((control1 == null) || (control2 == null)) {
		return false;
	}
	var valor1 = control1.value;
	var valor2 = control2.value;
	if(valor1 != valor2) {
		alert(msg);
		control2.focus();
		return false;
	}
	return true;
}

// validacion de patron
function f_validarDni(control) {
	if(control == null) {
		alert('Control: No existe.\nMensaje: ' + msg);
		return false;
	}
	var valor = control.value;
	var patron = /^\d{8}$/;
	if((valor.match(patron)) && (valor != '')) {
		return true;
	} else {
		alert('El Nro. de DNI es invalido.');
		control.focus();
		return false;
	}
}
function f_validarRuc(control) {
	if(control == null) {
		alert('Control: No existe.\nMensaje: ' + msg);
		return false;
	}
	var valor = control.value;
	var patron = /^\d{11}$/;
	if((valor.match(patron)) && (valor != '')) {
		return true;
	} else {
		alert('El Nro. de RUC es invalido.');
		control.focus();
		return false;
	}
}

function f_validarEmail(control) {
	if(control == null) {
		alert('Control: No existe.\nMensaje: ' + msg);
		return false;
	}
	var valor = control.value;
	var patron = '^([a-z0-9][a-z0-9_\\-\\.\\+]*)@([a-z0-9][a-z0-9\\.\\-]{0,63}\\.(com|org|net|biz|info|name|net|pro|aero|coop|museum|[a-z]{2,4}))$';
	if((valor.match(patron)) && (valor != '')) {
		return true;
	} else {
		alert('La direccion email es invalida.');
		control.focus();
		return false;
	}
}

function f_validarUsuario(control) {
	if(control == null) {
		alert('Control: No existe.\nMensaje: ' + msg);
		return false;
	}
	var valor = control.value;
	var patron = /^((?=.*\d)(?=.*[a-zA-Z]).{6,})$/;
	if((valor.match(patron)) && (valor != '')) {
		return true;
	} else {
		alert('El usuario debe contener solo numeros y letras, con un minimo de 6 caracteres.');
		control.focus();
		return false;
	}
}

function f_validarClaveAdmin(control) {
	if(control == null) {
		alert('Control: No existe.\nMensaje: ' + msg);
		return false;
	}
	var valor = control.value;
	var patron = /^((?=.*\d)(?=.*[a-zA-Z]).{6,})$/;
	if((valor.match(patron)) && (valor != '')) {
		return true;
	} else {
		alert('La clave debe contener solo numeros y letras, con un minimo de 6 caracteres.');
		control.focus();
		return false;
	}
}

function f_validarClaveUsuario(control) {
	if(control == null) {
		alert('Control: No existe.\nMensaje: ' + msg);
		return false;
	}
	var valor = control.value;
	var patron = /^((?=.*\d)(?=.*[a-zA-Z]).{4,10})$/;
	if((valor.match(patron)) && (valor != '')) {
		return true;
	} else {
		alert('La clave debe contener solo numeros y letras, con un minimo de 4 y un maximo de 10 caracteres.');
		control.focus();
		return false;
	}
}

function f_validarAlphanumerico(control, nombreCampo) {
	if(control == null) {
		alert('Control: No existe.\nMensaje: ' + msg);
		return false;
	}
	var valor = control.value;
	var patron = /^\d+(\-)?\d*$/;
	if((valor.match(patron)) && (valor != '')) {
		return true;
	} else {
		alert(nombreCampo + ": " + "Solo se aceptan numeros enteros y/o letras.");
		control.focus();
		return false;
	}
}

function f_validarEntero(control, nombreCampo) {
	if(control == null) {
		alert('Control: No existe.\nMensaje: ' + msg);
		return false;
	}
	var valor = control.value;
	var patron = /^(?:\+|-)?\d+$/;
	if((valor.match(patron)) && (valor != '')) {
		return true;
	} else {
		alert(nombreCampo + ": " + "Solo se aceptan numeros enteros.");
		control.focus();
		return false;
	}
}

function f_validarDecimal(control, nombreCampo) {
	if(control == null) {
		alert('Control: No existe.\nMensaje: ' + msg);
		return false;
	}
	var valor = control.value;
	var patron = /^\d+(\.)?\d*$/;
	if((valor.match(patron)) && (valor != '')) {
		return true;
	} else {
		alert(nombreCampo + ": " + "Solo se aceptan numeros decimales (usar separador '.').");
		control.focus();
		return false;
	}
}

function f_validarCoordenadaGeografica(control, nombreCampo) {
	if(control == null) {
		alert('Control: No existe.\nMensaje: ' + msg);
		return false;
	}
	var valor = control.value;
	var patron = /^(\-)?((\d{2}).(\d{6}))$/;
	if((valor.match(patron)) && (valor != '')) {
		return true;
	} else {
		alert(nombreCampo + ": " + "La coordenada debe tener el formato '(-)xx.yyyyyy'.");
		control.focus();
		return false;
	}
}

function f_validarTiempo(control, nombreCampo) {
	if(control == null) {
		alert('Control: No existe.\nMensaje: ' + msg);
		return false;
	}
	var valor = control.value;
	var patron = /^((0[1-9]|1\d)|(2[0-3]\d)):([0-5]\d)$/;
	if((valor.match(patron)) && (valor != '')) {
		return true;
	} else {
		alert(nombreCampo + ": " + "La hora debe tener el formato 'xx:yy' (24 h).");
		control.focus();
		return false;
	}
}

// validacion de evento
function e_soloAlphanumerico(evt) {
	evt = (evt) ? evt : window.event;
	var key = (evt.which) ? evt.which : evt.keyCode;
	return ((key <= 13) || (key >= 48 && key <= 57) || (key >= 65 && key <= 90) || (key >= 97 && key <= 122));
}

function e_soloEntero(evt) {
	evt = (evt) ? evt : window.event;
	var key = (evt.which) ? evt.which : evt.keyCode;
	return ((key <= 13) || (key >= 48 && key <= 57));
}

function e_soloDecimal(evt) {
	evt = (evt) ? evt : window.event;
	var key = (evt.which) ? evt.which : evt.keyCode;
	return ((key <= 13) || (key >= 48 && key <= 57) || (key == 46));
}

function e_soloCoordenadaGeografica(evt) {
	evt = (evt) ? evt : window.event;
	var key = (evt.which) ? evt.which : evt.keyCode;
	return ((key <= 13) || (key >= 48 && key <= 57) || (key == 45) || (key == 46));
}

function e_numeroLicencia(evt) {
	evt = (evt) ? evt : window.event;
	var key = (evt.which) ? evt.which : evt.keyCode;
	return ((key <= 13) || (key >= 48 && key <= 57) || (key >= 65 && key <= 90) || (key >= 97 && key <= 122) || (key == 45));
}

function e_numeroExpediente(evt) {
	evt = (evt) ? evt : window.event;
	var key = (evt.which) ? evt.which : evt.keyCode;
	return ((key <= 13) || (key >= 48 && key <= 57) || (key == 45));
}

function e_tiempo(evt) {
	evt = (evt) ? evt : window.event;
	var key = (evt.which) ? evt.which : evt.keyCode;
	return ((key <= 13) || (key >= 48 && key <= 57) || (key == 58));
}

function e_desabilitarEnter(evt) {
	evt = (evt) ? evt : window.event;
	var key = (evt.which) ? evt.which : evt.keyCode;
	return (key == 13) ? false : true;
}

// utiles
function u_abrirVentana(url, titulo, width, height) {
	var url_ = (url !== 'undefined') ? url : false;
	if(!url) {
		window.close();
	}
	var titulo_ = (titulo !== 'undefined') ? titulo : 'Licencia de Funcionamiento';
	var width_ = (width !== 'undefined') ? width : '100';
	var height_ = (height !== 'undefined') ? height : '100';
	window.open(url_,titulo_,'scrollbars=yes,resizable=yes,width=' + width_ + ',height=' + height_ + ',top=100,left=200,status=no,location=no,toolbar=no');
}

function u_redireccionar(url) {
	var url_ = (url !== 'undefined') ? url : false;
	if(!url) {
		return false;
	}
	window.location.href = url;
}

function u_showdivs(divname) {
	var div = $(divname);
	div.style.display = (div.style.display == 'block') ? 'none' : 'block';
}

function u_seleccionarItem(id) {
	var elemento = $(id);
	elemento.checked = (elemento.checked) ? false : true;
}

function u_seleccionarItemUnico(id) {
	var checks = $$('input.validarCheck');
	for(var i=0; i<checks.length; i++) {
		checks[i].checked = false;
	}
	u_seleccionarItem(id);
}

function u_seleccionarTodos(elemento) {
	var checks = $$('input.validarCheck');
	for(var i=0; i<checks.length; i++) {
		checks[i].checked = elemento.checked;
	}
}

function u_toggleClassExpandirContraer(control) {
	if(control == null) {
		alert('Control: No existe.\nMensaje: ' + msg);
		return false;
	}
	if(control.className.search(/expanded/i) >= 0) {
		control.removeClassName('expanded');
		control.addClassName('collapsed');
	} else {
		control.addClassName('expanded');
		control.removeClassName('collapsed');
	}
}

function u_cerrar() {
	window.close();
}

function u_cerrarDelay(el, milsec) {
	var timer = milsec/1000;
	setTimeout("u_actualizarTimer('" + el + "', '" + timer + "')", 1000);
	setTimeout("window.close();", milsec);
}

function u_actualizarTimer(el, timer) {
	timer = timer * 1;
	timer--;
	if((el !== "") && ($(el) !== 'undefined')) {
		$(el).update(timer);
	}
	setTimeout("u_actualizarTimer('" + el + "', '" + timer + "')", 1000);
}

function u_agregarMsgLoad(el, theme) {
	var theme = theme !== '' ? theme : 'blue';
	var className = null;
	switch(theme) {
		case 'blue': 	className = 'loadingMessageBlue';break;
		case 'gray': 	className = 'loadingMessageGray';break;
		default: 		className = 'loadingMessageBlue';
	}
	if(el !== '') {
		$(el).innerHTML = "<div class='" + className + "' style='display: inline;' title='Cargando...'></div>";
	}
}

function u_quitarMsgLoad(el) {
	if(el !== '') {
		$(el).innerHTML = "";
	}
}

function u_mostrarIndicadorOligatorio() {
	var clase = "datoObligatorio";
	var elementos = $$('*.' + clase);
	if(elementos.length > 0) {
		var cont = null;
		for(var i=0; i < elementos.length; i++) {
			cont = elementos[i].innerHTML;
			elementos[i].innerHTML = cont + "&nbsp;<font color='red' class='dato_obligatorio'>*</font>";
		}
	}
}

function u_mostrarSoloLectura() {
	var clase = "soloLectura";
	var elementos = $$('*.' + clase);
	if(elementos.length > 0) {
		var cont = null;
		for(var i=0; i < elementos.length; i++) {
			elementos[i].readonly = true;
			elementos[i].disabled = true;
		}
	}
}

function u_initGridTable() {
	jQuery(function() {
		jQuery("table.gridTable tr").mouseover(function() {
			if(!(this.className.search(/row-selected/i) >= 0)) {
				this.className = 'row-over';
			}
		});
		jQuery(".row").mouseout(function() {
			if(!(this.className.search(/row-selected/i) >= 0)) {
				this.className = 'row';
			}
		});
		jQuery(".row").click(function() {
			if(this.className.search(/row-selected/i) >= 0) {
				this.removeClassName('row-selected');
			} else {
				this.className = 'row-selected';
			}
		});
	});
}

function u_agregarFileList(model, list_id, file_id) {
	li = new Element('li');
	file = new Element('input', {'id':file_id, 'type':'file', 'size':'80', 'name':'data[' + model + '][files][]'});
	li.appendChild(file);
	$(list_id).appendChild(li);
}

function u_toggleButton(toggle_id, div_id) {
	$(toggle_id).onclick = function() {
		this.toggleClassName('icon-toggle-collapsed');
		Effect.toggle(div_id, 'blind', {duration: 0.5});
	}
//	$(toggle_id).onmouseover = function() {
//		this.toggleClassName('icon-toggle-over');
//		if(this.className.search(/icon-toggle-collapsed/i) >= 0) {
//			this.removeClassName('icon-toggle-collapsed');
//			this.toggleClassName('icon-toggle-collapsed-over');
//		} else {
//			if(this.className.search(/icon-toggle-collapsed-over/i) >= 0) {
//				this.removeClassName('icon-toggle-collapsed-over');
//				this.toggleClassName('icon-toggle-collapsed');
//			} 
//		}
//	}
//	$(toggle_id).onmouseout = function() {
//		this.toggleClassName('icon-toggle-over');
//	}
}

function js_sombra(el, bg_color, cursor){
	el.bgColor = bg_color;
	el.style.cursor = cursor;
}

function updateContentLayout(url) {
	var el = "content";
	new Ajax.Updater(el, url, {
		method: 'get', 
		onLoaded: function() {
			setTimeout("u_initGridTable();", 2000);
		}
	});
}

function updateContainerLayout(url) {
	var el = "container";
	new Ajax.Updater(el, url, {
		method: 'get', 
		onLoaded: function() {
			setTimeout("u_initGridTable();", 2000);
		}
	});
}

function u_ocultarFlashMessage() {
	$('flashMessage').fade();
}

function u_agregarFlashMessageCloseAction(sec) {
	if($('flashMessage')) {
		var cnt = $('flashMessage').innerHTML;
		$('flashMessage').innerHTML = cnt + "<span class='close' onclick='u_ocultarFlashMessage();'></span>";
		setTimeout("u_ocultarFlashMessage();", sec * 1000);
	}
}

function u_strpos(haystack, needle, offset) {
    var i = (haystack + '').indexOf(needle, (offset || 0));
    return i === -1 ? false : i;
}
