/* FUNCIONES PARA OBTENER VARIABLES CON AJAX */
/* codigo obtenido de http://www.ajaxhispano.com/tutorial-manual-ajax-ejemplos-metodo-GET-POST-principiantes.html bajo la licencia GNU/GPL */

function creaAjax(){
	var objetoAjax=false;
	try {
		/*Para navegadores distintos a internet explorer*/
		objetoAjax = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			/*Para explorer*/
			objetoAjax = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch (E) {
			objetoAjax = false;
		}
	}

	if (!objetoAjax && typeof XMLHttpRequest!='undefined') {
		objetoAjax = new XMLHttpRequest();
	}
	
	
	return objetoAjax;
}

function dato_doc(){
	//donde se mostrará lo resultados
	divResultado = document.getElementById('resultado');
	divFormulario = document.getElementById('formulario');
	//valores de los inputs
	id=document.n_aseguradora.t_documento.value;

	alert(id)
	//instanciamos el objetoAjax
	ajax=creaAjax();
	//usando del medoto POST
	//archivo que realizará la operacion
	//actualizacion.php
	//ajax.open("POST", "actualizacion.php",true);
	//ajax.open("POST","prueba.php",true);

	ajax.onreadystatechange=function(){
																				if (ajax.readyState==4) {
																					//mostrar los nuevos registros en esta capa
																					//divResultado.innerHTML = ajax.responseText
																					//mostrar un mensaje de actualizacion correcta
																					//divFormulario.innerHTML = "<p style=\"border:1px solid red; width:400px;\">
																					//La actualizaci&oacute;n se realiz&oacute; correctamente</p>";
																				}
	}
	//muy importante este encabezado ya que hacemos uso de un formulario
	ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	//enviando los valores
	ajax.send("t_documento="+id)
}

function enviarDatosEmpleado(){
	//donde se mostrará lo resultados
	divResultado = document.getElementById('resultado');
	divFormulario = document.getElementById('formulario');
	//valores de los inputs
	id=document.frmempleado.idempleado.value;
	nom=document.frmempleado.nombres.value;
	dep=document.frmempleado.departamento.value;
	suel=document.frmempleado.sueldo.value;

	//instanciamos el objetoAjax
	ajax=creaAjax();
	//usando del medoto POST
	//archivo que realizará la operacion
	//actualizacion.php
	//ajax.open("POST", "actualizacion.php",true);
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
			//mostrar los nuevos registros en esta capa
			//divResultado.innerHTML = ajax.responseText
			//mostrar un mensaje de actualizacion correcta
			//divFormulario.innerHTML = "<p style=\"border:1px solid red; width:400px;\">La actualizaci&oacute;n se realiz&oacute; correctamente</p>";
		}
	}
	//muy importante este encabezado ya que hacemos uso de un formulario
	ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	//enviando los valores
	ajax.send("idempleado="+id+"&nombres="+nom+"&departamento="+dep+"&sueldo="+suel)
}

function FAjax (url,valores,metodo) {
	var ajax=creaAjax();
	
	/*Creamos y ejecutamos la instancia si el metodo elegido es POST*/
	if (metodo.toUpperCase()=='POST'){
		ajax.open ('POST', url, true);
		ajax.onreadystatechange = function(){
																					if (ajax.readyState==1) {
																						//capaContenedora.innerHTML="Cargando.......";
																					} else if (ajax.readyState==4){
																						if(ajax.status==200) {
																							document.getElementById(capa).innerHTML=ajax.responseText;
																						} else if(ajax.status==404) {
																							capaContenedora.innerHTML = "La direccion no existe";
																						} else {
																							capaContenedora.innerHTML = "Error: ".ajax.status;
																						}
																					}
																				}
		ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		ajax.send(valores);
		return;
	}
	/*Creamos y ejecutamos la instancia si el metodo elegido es GET*/
	if (metodo.toUpperCase()=='GET'){
		ajax.open ('GET', url, true);
		ajax.onreadystatechange = function(){
																					if (ajax.readyState==1) {
																						capaContenedora.innerHTML="Cargando.......";
																					} else if (ajax.readyState==4){
																						if (ajax.status==200) {
																							document.getElementById(capa).innerHTML=ajax.responseText;
																						} else if(ajax.status==404) {
																							capaContenedora.innerHTML = "La direccion no existe";
																						} else {
																							capaContenedora.innerHTML = "Error: ".ajax.status;
																						}
																					}
																				}
		ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		ajax.send(null);
		return
	}
} 
/* FIN DE AJAX */

function change(id){
	ID = document.getElementById(id);
	if (ID.style.display == "") {
		ID.style.display = "none";
	} else {
		ID.style.display = "";
	}
}

function mmLoadMenus() {
	if (window.mm_menu_0907120409_0) return;
	window.mm_menu_0907120409_0=new Menu("root",152,18,"Verdana, Arial, Helvetica, sans-serif",12,"#FFFFFF","#FFFFFF","#CCCCCC","#000099",
	"left","middle",3,0,500,-5,7,true,true,true,0,false,true);
	mm_menu_0907120409_0.addMenuItem("mapa","location='javascript:imprimirPagina(this.form)'");
	mm_menu_0907120409_0.addMenuItem("comercializadores","location='fichas/informe02.php?sublinea=17&Submit=Comercializadores'");
	mm_menu_0907120409_0.addMenuItem("fichas tecnicas","location='fichas/informe02.php?sublinea=17&Submit=f_tecnicas'");
	mm_menu_0907120409_0.addMenuItem("fichas aplicante","location='fichas/informe02.php?sublinea=17&Submit=f_aplicante'");
	mm_menu_0907120409_0.hideOnMouseOut=true;
	mm_menu_0907120409_0.bgColor='#999999';
	mm_menu_0907120409_0.menuBorder=0;
	mm_menu_0907120409_0.menuLiteBgColor='#999999';
	mm_menu_0907120409_0.menuBorderBgColor='#CCCCCC';
	mm_menu_0907120409_0.writeMenus();
} // mmLoadMenus()

function MM_showHideLayers() { //v6.0
	MM_reloadPage(true);
	//document.reload(Tim_FoleyII.php);
	var i,p,v,obj,args=MM_showHideLayers.arguments;
	for (i = 0; i < (args.length - 2); i += 3) {
		if ((obj = MM_findObj(args[i])) != null) {
			v = args[i + 2];
			if (obj.style) {
				obj = obj.style;
				v = (v == 'show') ? 'visible' : (v == 'hide') ? 'hidden' : v;
			}
			obj.visibility = v;
		}
	}
}

function MM_reloadPage(init) { //reloads the window if Nav4 resized
	if (init == true) 
		with (navigator) {
			if ((appName == "Netscape") && (parseInt(appVersion) == 4)) {
				document.MM_pgW = innerWidth;
				document.MM_pgH = innerHeight;
				onresize = MM_reloadPage;
			}
		} else if (innerWidth != document.MM_pgW || innerHeight != document.MM_pgH) {
			location.reload();
		}
}

MM_reloadPage(true);

function MM_findObj(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;
}

function validar_datosbas(form) {
	
	if (!valida(form.t_cod, '..::Por Favor Digite el Código::..',false)) return false;
	if (!valida(form.t_descrip, '..::Por Favor Digite la Descripción::..',false)) return false;
	
	return true;
}

function validar_datosbashor(form) {
	
	
	if (!valida(form.s_cia, '..::Por Favor Seleccione una Compañia::..',false)) return false;
	if (!valida(form.s_dep, '..::Por Favor Seleccione una Unidad Organizacional::..',false)) return false;
	if (!valida(form.s_jornada, '..::Por Favor Seleccione una Jornada::..',false)) return false;
	if (!valida(form.s_dia, '..::Por Favor Seleccione un Dia::..',false)) return false;
	if (!valida(form.hora_ini1, '..::Por Favor Ingrese una Hora Inicial para la Primera Jornada::..',false)) return false;
	if (!valida(form.hora_fin1, '..::Por Favor Ingrese una Hora Final para la Primera Jornada::..',false)) return false;

	
	
	return true;
}

function validar_datosobj(form) {
	var ok=true;
	
	if(form.t_cod.value=="" &&  form.t_descrip.value=="" && form.s_cia.value==0 && form.s_tipo.value==0) {
		alert("..:: Por favor complete los campos obligatorios, marcados (*) ::..");
	} else {
		if(form.t_cod.value=="") {
			alert("..:: Por Favor Digite Código ::..");
			foco(form.t_cod);
			ok=false;
		}
		
		if(form.t_descrip.value=="") {
			alert("..:: Por Favor Digite la Descripción del Objetivo ::..");
			foco(form.t_descrip);
			ok=false;
		}
		
		if(form.s_cia.value==0) {
			alert("..:: Por Favor Seleccione la compañia ::..");
			ok=false;
		}
		
		if(form.s_tipo.value==0) {
			alert("..:: Por Favor Seleccione la clasificación ::..");
			ok=false;
		}
	}// fin de else
	return ok;
}

/* FUNCION VALIDADORA DE LOS INDICADORES Y DATOS ENVIADOS DESDE EL FORMULARIO INDICADORES */
function validar_datosind(form) {
	
	var ok=true;
	
	if(form.t_cod.value=="" && form.t_descrip.value=="" && form.s_cia.value==0 && form.s_unidad.value==0 && form.s_obj.value==0 && 
	form.s_per.value==0) {
		alert("..:: Por favor complete todos los datos, son obligatorios ::..");
	} else {
		if(form.t_cod.value=="") {
			alert("..:: Por Favor Digite Código ::..");
			foco(form.t_cod);
			ok=false;
		}
		
		if(form.t_descrip.value=="") {
			alert("..:: Por Favor Digite la Descripción del Indicador ::..");
			foco(form.t_descrip);
			ok=false;
		}
		
		if(form.s_cia.value==0) {
			alert("..:: Por Favor Seleccione la Compañia ::..");
			ok=false;
		}
		
		if(form.s_unidad.value==0) {
			alert("..:: Por Favor Seleccione la Unidad de Medida ::..");
			ok=false;
		}
		
		if(form.s_obj.value==0) {
			alert("..:: Por Favor Seleccione El objetivo a que Pertenece el Indicador ::..");
			ok=false;
		}
		
		if(form.t_minferior.value=="") {
			alert("..:: Por Favor Digite un Valor para la Meta Inferior ::..");
			ok=false;
		}
		
		if(form.t_mesperada.value=="") {
			alert("..:: Por Favor Digite un Valor para la Meta Esperada ::..");
			ok=false;
		}
		
		if(form.t_msuperior.value=="") {
			alert("..:: Por Favor Digite un Valor para la Meta Superior ::..");
			ok=false;
		}
		
		if(form.s_msuperior.value==0) {
			alert("..:: Por Favor Digite un Valor para la Meta Superior ::..");
			ok=false;
		}
		
		if(form.s_minferior.value==0) {
			alert("..:: Por Favor Digite un Valor para la Meta Inferior ::..");
			ok=false;
		}
		
		if(form.s_mesperada.value==0) {
			alert("..:: Por Favor Digite un Valor para la Meta Esperada ::..");
				ok=false;
		}
		
		if(form.s_unidad.value=='POR') {
			if (form.t_msuperior.value>100 || form.t_mesperada.value>100 || form.t_minferior.value>100) {
					alert("..:: Por Favor Digite un Valor Valido de meta ::..");
					ok=false;
			}
		}
		
		if(form.s_unidad.value=='POR') {
			if(form.t_msuperior.value>100 || form.t_mesperada.value>100 || form.t_minferior.value>100) {
				alert("..:: Por Favor Digite un Valor Valido de meta ::..");
				ok=false;
			}
		}
		
		if(form.s_unidad.value=='PTO') {
			if(form.t_msuperior.value>10 || form.t_mesperada.value>10 || form.t_minferior.value>10) {
				alert("..:: Por Favor Digite un Valor Valido de meta ::..");
				ok=false;
			}
		}
	}// fin de else
	return ok;
}

function foco(elemento) {
	elemento.focus();
	
	if (elemento.type == 'text') {
		elemento.select();
	}
	
}

function valida(campo,mensaje,fl_cero) {
	if (campo.value=='') {
		mensaje_nv('ERROR',mensaje,Ext.MessageBox.OK,Ext.MessageBox.ERROR,'')
		foco(campo);
		return false;
	}
	
	if (fl_cero) {
		if (campo.value=='0') {
			mensaje_nv('ERROR',mensaje,Ext.MessageBox.OK,Ext.MessageBox.ERROR,'')
			foco(campo);
			return false;
		}
	}
	
	return true;
}

/* FUNCION PARA VALIDAR LOS CAMPOS MAIL O CORREO */
function correo(valor) {
	var cad=valor.value;
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(cad)){
		return true;
	} else {
		mensaje_nv('ERROR','..:: El Correo Digitado no es Valido ::..',Ext.MessageBox.OK,Ext.MessageBox.ERROR,'');
		foco(valor);
		return false;
	}
}//cierra funcion

function mensaje(a,m,p) {
	if (a != 1) {
		if (p == 1) {
			mensaje_nv('ERROR','..:: Requiere autorización de adición para este menú, código ' + m + ' ::..',Ext.MessageBox.OK,
			Ext.MessageBox.ERROR,'');
			return false;
		}
		if (p == 2) {
			mensaje_nv('ERROR','..:: Requiere autorización de modificación para este menú, código ' + m + ' ::..',Ext.MessageBox.OK,
			Ext.MessageBox.ERROR,'');
			return false;
		}
	} else {
		return true;
	}
	
}

/* SCRIPT PARA MENSAJE DE CONFIRMACION */
function confirmacion(form) {
	
	var a=form.mod.value;
	var m=form.menu.value;
	var p=2;
	var dato2="";
	if (!mensaje(a,m,p)) return false;
	
	if (!valida(form.t_cod, '..::Por Favor Digite el Código::..',false)) return false;
	if (!valida(form.t_descrip, '..::Por Favor Digite la Descripción::..',false)) return false;
	
	mensaje_nv('PREGUNTA',"¿Desea Modificar el Registro?",Ext.MessageBox.YESNO,Ext.MessageBox.QUESTION,'-2',form,'yes');
	return false;
}
function confirmacionhor(form) {
	
	var a=form.mod.value;
	var m=form.menu.value;
	var p=2;
	var dato2="";
	if (!mensaje(a,m,p)) return false;
	
	if (!valida(form.t_cod, '..::Por Favor Digite el Código::..',false)) return false;
	if (!valida(form.t_descrip, '..::Por Favor Digite la Descripción::..',false)) return false;
	
	mensaje_nv('PREGUNTA',"¿Desea Modificar el Registro?",Ext.MessageBox.YESNO,Ext.MessageBox.QUESTION,'-2',form,'yes');
	return false;
}

function confirmacion2(form) {
	
	if (form.t_distrito.value == "" && form.s_distrito.value != "") {
		var entrar = confirm("¿Desea Eliminar El Distrito Seleccionado?")
		if (!entrar) {
			return false;
		} else { 
			return true
		};
	}
	return true;
}

function confirmacion_ndato(form) {
	if (form.t_cod.value!="" && form.t_descrip.value!="") {
		var entrar = confirm("¿Desea Adicionar el Registro?")
		if (!entrar) {
			return false;
		} else {
			return true;
		}
	}
}

function documento(pagina, campo,op){
	var t_documento = campo.value;
	pagina = pagina+"?t_documento=" + t_documento + '&enfocar=s_nombre' + op;
	window.location = pagina;
}

function mayuscula(campo){
	campo.value=campo.value.toUpperCase();
}

function depto(pagina){
	var t_deptoexp = window.document.form_ndirectorio.s_deptoexp.value;
	pagina = pagina + "?deptoexp=" + t_deptoexp;
	window.location = pagina;
}

/**************************************************************
Máscara de entrada. Script creado por Tunait! (21/12/2004)
Si quieres usar este script en tu sitio eres libre de hacerlo con la condición de que permanezcan intactas estas líneas, osea, 
los créditos.
No autorizo a distribuír el código en sitios de script sin previa autorización
Si quieres distribuírlo, por favor, contacta conmigo.
Ver condiciones de uso en http://javascript.tunait.com/
tunait@yahoo.com 
****************************************************************/
var patron = new Array(2,2,4)
var patron2 = new Array(1,3,3,3,3)
function mascara(d,sep,pat,nums){
	if(d.valant != d.value){
		val = d.value
		largo = val.length
		val = val.split(sep)
		val2 = ''
		
		for(r=0;r<val.length;r++){
			val2 += val[r]
		}
		
		if(nums){
			for(z=0;z<val2.length;z++){
				if(isNaN(val2.charAt(z))&&val2.charAt(z)!='.'&&val2.charAt(z)!=','&&val2.charAt(z)!='-'&&val2.charAt(z)!=':'){
					letra = new RegExp(val2.charAt(z),"g")
					val2 = val2.replace(letra,"")
				}
			}
		}
		
		val = ''
		val3 = new Array()
		
		for(s=0; s<pat.length; s++){
			val3[s] = val2.substring(0,pat[s])
			val2 = val2.substr(pat[s])
		}
		
		for(q=0;q<val3.length; q++){
			if(q ==0){
				val = val3[q]
			} else {
				if(val3[q] != ""){
					val += sep + val3[q]
				}
			}
		}
		
		d.value = val
		d.valant = val
	}
}

/**************** la siguiente función fue obtenida de http://www.forosdelweb.com/f13/validar-solo-numeros-no-permitir-copy-paste-369421 */
function validarNum(e) {
	tecla = (document.all) ? e.keyCode : e.which;
	if (tecla == 8) return true;
	patron = /\d/;
	te = String.fromCharCode(tecla);
	return patron.test(te);
}

/********************************* FIN DE LA FUNCION *********************************************************************************/
/*********************************FUNCION PARA AUMENTAR VALORES A CAMPO******************************************************/
function aumento_numero(campo, max) {
	var valor = campo.value;
	valor ++;
	if (valor > max) valor = max;
	campo.value = valor;
	alert(valor);
}

function nombre(campo, nombre){
	campo.value = nombre.value;
}

function nombre_format(campo, nombre){
	campo.value = nombre.value;
	formatNumber(campo,',','');
}

function accion_forma(form, accion){
	
	form.action=accion;
}

function image(campo, valor){
	campo.src = valor;
}

function select (valor,select) {
	var combo = select.options.length;
	for (var i=0;i<combo;i++) {
		if (valor==select.options[i].value) {
			select.selectedIndex = i;
		}
	}
}

function nombres(url,element_id,pri_ape,se_ape,pri_nom,se_nom){
	var peticion = false;
	var testPasado = false;
	try {
		peticion = new XMLHttpRequest();
	} catch (trymicrosoft) {
		try {
			peticion = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (othermicrosoft) {
			try {
				peticion = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (failed) {
				peticion = false;
			}
		}
	}
	//Obtenemos el contenido del div
	//donde se cargaran los resultados
	var element =  document.getElementById(element_id);
	//Obtenemos el valor seleccionado del combo anterior
	//var valordepende = document.getElementById(comboAnterior)
	//var x = comboAnterior.value
	//construimos la url definitiva
	//pasando como parametro el valor seleccionado
	var fragment_url = url+'?pri_ape='+pri_ape+'&se_ape='+se_ape+'&pri_nom='+pri_nom+'&se_nom='+se_nom;
	//abrimos la url
	peticion.open("GET", fragment_url); 
	peticion.onreadystatechange = function(){ 
																							if (peticion.readyState == 4) {
																								//escribimos la respuesta
																								element.innerHTML = peticion.responseText;
																							}
																					}
	peticion.send(null);
}

function cargarCombo (url, depto, ciudad, element_id,nombre) {
	var peticion = false;
	var testPasado = false;
	peticion=object();
	//Obtenemos el contenido del div
	//donde se cargaran los resultados
	var element =  document.getElementById(element_id);
	//Obtenemos el valor seleccionado del combo anterior
	//var valordepende = document.getElementById(comboAnterior)
	//var x = comboAnterior.value
	//construimos la url definitiva
	//pasando como parametro el valor seleccionado
	var fragment_url=url+'?depto='+depto+'&municipio='+ciudad+'&nombre='+nombre;
	element.innerHTML = '<img src="Imagenes/loading.gif" />'; 
	//abrimos la url
	peticion.open("GET", fragment_url); 
	peticion.onreadystatechange = function(){ 
																						if (peticion.readyState == 4) {
																							//escribimos la respuesta
																							element.innerHTML = peticion.responseText;
																						}
																					} 
	
	peticion.send(null); 
}

function object() {
	var peticion = false;
	var testPasado = false;
	try {
		peticion = new XMLHttpRequest();
	} catch (trymicrosoft) {
		try {
			peticion = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (othermicrosoft) {
				try {
					peticion = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (failed) {
					peticion = false;
				}
		}
	}
	if (!peticion) alert("ERROR AL INICIALIZAR!");
	return peticion;
}

function cambio (campo,valor) {
	var combo = campo.options.length; 
	valor=unformatNumber(valor);
	for (var i=0;i<combo;i++) {
		if (valor==campo.options[i].value) {
			campo.selectedIndex = i;
			break;
		}
	}
	if (i==combo) {
		campo.selectedIndex=1;
	}
}

function formatNumber(campo, sep, prefix){
	prefix = prefix || '';
	num = unformatNumber(campo.value);
	num += '';
	var splitStr = num.split('x');
	var splitLeft = splitStr[0];
	var splitRight = splitStr.length > 1 ? 'x' + splitStr[1] : '';
	var regx = /(\d+)(\d{3})/;
	
	if (campo.value != ''&&campo.value != '-') {
  	while (regx.test(splitLeft)) {
  		splitLeft = splitLeft.replace(regx, '$1' + sep + '$2');
  	}
  	
  	campo.value = prefix + splitLeft + splitRight;
  }
}

function unformatNumber(num) {
	return num.replace(/([^0-9\-\.])/g,'')*1;
}

/*
 * funcion para dar formato a las fechas
 * adquirida de http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_20506787.html
 */

function checkPartialDate( obj ){
  var partialDateValidator = /^(\d{0,2}(-(\d{0,2}(-(\d{0,4})?)?)?)?)/;
  var tmp = partialDateValidator.exec( obj.value );
  obj.value = tmp[1];
  if( obj.value.length == 2 || obj.value.length == 5 )
          obj.value += '-';
}

/** CODIGO GENERADO PARA VALIDAR LOS DECIMALES DIGITADOS***/
function valida_dec(campo,valor,decimales,digitos) {
	var dec_per =parseInt(decimales); 
	if (isNaN(valor) || valor == '') {
		alert('..:: Por favor ingrese la cantidad o Peso, separada con punto si tiene decimales ::..');
		campo.focus();
	} else {
		var total=valor.length;
		if (valor.indexOf('.') == -1) valor += ".";
		var decimales = valor.substring(valor.indexOf('.')+1, valor.length);
		if(decimales.length == 0 && total > digitos) {
			alert ("..:: Por favor Introduzca un numero con "+digitos+" digitos y si tiene decimales " + dec_per + " decimales, maximo ::..");
			campo.focus();
			campo.value="";						
		}
		
		if (decimales.length > dec_per) {
			alert ("..:: Por favor Introduzca un numero con " + dec_per + " decimales, maximo ::..");
			campo.value="";
			campo.focus();
		}
	}
}

/*************FUNCION PARA BUSCAR UN VALOR EN ARREGLO RETORNA -1 SI NO ENCUENTRA EL VALOR************/
function buscar_valor(arreglo,valor) {
	for (var i=0;i<arreglo.length;i++) {
		if (valor==arreglo[i]) {
			return i;
			break;
		}
	}
	return -1;
}

/*************FUNCION PARA MOVER AL FINAL UN VALOR EN UN ARREGLO**********/
Array.prototype.moverAlFinal = function(b,ini) {
	var yo = this;
	var longitudArray = yo.length;
	if (b == ini) {
		return yo.rotarI();
	} else {
		if (b < (yo.length - 1)) {
			principio = yo.slice(0, b);
			fin = yo.slice(b, longitudArray).rotarI();
			yo = principio.concat(fin);
			return principio.concat(fin);
		} else {
			return yo;
		}
	}
}

/*************FUNCION PARA ROTAR A LA IZQUIERDA UN VALOR EN UN ARREGLO**********/
Array.prototype.rotarI = function() {
	var yo = this;
	var primero = yo.shift();
	yo[yo.length] = primero;
	return yo;
}

/*************FUNCION PARA DETERMINAR LA SEGURIDAD DE UNA CONTRASEÑA**********/
function seguridad_clave(clave){
	var seguridad = 0;
	if (clave.length!=0){
		if (tiene_numeros(clave) && tiene_letras(clave)) seguridad += 30;
		
		if (tiene_minusculas(clave) && tiene_mayusculas(clave)) seguridad += 30;
		
		if (clave.length >= 4 && clave.length <= 5){
			seguridad += 10;
		} else {
			if (clave.length >= 6 && clave.length <= 8){
				seguridad += 30;
			} else {
				if (clave.length > 8){
					
					seguridad += 40;
				}
			}
		}
	}
	return seguridad
}

/*************FUNCION PARA DETERMINAR SI TEXTO TIENE NUMEROS**********/
function tiene_numeros(texto){
	var numeros="0123456789";
	for (i = 0; i < texto.length; i++) {
		if (numeros.indexOf(texto.charAt(i), 0) != -1) return true;
	}
	return false;
}

/*************FUNCION PARA DETERMINAR SI TEXTO TIENE LETRAS**********/
function tiene_letras(texto){
	var letras="abcdefghyjklmnñopqrstuvwxyz";
	texto = texto.toLowerCase();
	for(i=0; i<texto.length; i++){
		if (letras.indexOf(texto.charAt(i), 0) != -1) {
			return true;
		}
	}
	return false;
}

/*************FUNCION PARA DETERMINAR SI TEXTO TIENE LETRAS MINISCULAS**********/
function tiene_minusculas(texto){
	var letras="abcdefghyjklmnñopqrstuvwxyz";
	for(i=0; i<texto.length; i++){
		if (letras.indexOf(texto.charAt(i),0)!=-1) return true;
	}
	return false;
}

/*************FUNCION PARA DETERMINAR SI TEXTO TIENE LETRAS MAYUSCULAS**********/
function tiene_mayusculas(texto){
	var letras="abcdefghyjklmnñopqrstuvwxyz";
	letras=letras.toUpperCase();
	for(i=0; i<texto.length; i++){
		if (letras.indexOf(texto.charAt(i),0)!=-1) return 1;
	}
	return 0;
}

/*************FUNCION PARA VERIFICAR QUE SEA NUMERICO UN CAMPO**********/
function es_numero(campo){
	if (isNaN(campo.value)) {
		alert('..:: Valor Digitado No Es Numerico ::..');
		campo.value='';
	}
}

/***FUNCIÓN PARA MOSTRAR MENSAJES*/
function mensaje_nv(titulo,mensaje,boton,icono,pagina,formulario,vl_envia) {
	Ext.MessageBox.show({
		title: titulo,
		msg: mensaje,
		buttons: boton,
		icon: icono,
		fn: showResult
	});
	
	function showResult(btn){
		if (pagina == '-2') {
		
			var valor = Ext.example.devuelve('{0}', btn);
			formulario.sino.value = valor;
			if (vl_envia == valor) {
				for (i = 0; i < formulario.elements.length; i++) {
					if (formulario.elements[i].disabled) 
						formulario.elements[i].disabled = false;
				}
				formulario.submit();
			}
		} else if (pagina == '-3') {
			var valor = Ext.example.devuelve('{0}', btn);
			if (valor=='yes') {
				Ext.example.redirecciona(vl_envia);
			} else {
				Ext.example.redirecciona(formulario);
			}
		} else {
			Ext.example.redirecciona(pagina);
		}
	};
}

function banner() {
	var aleatorio=Math.round(3*Math.random());
	if(aleatorio == 0 || aleatorio > 2) aleatorio=1;
	var imagen;
	if (screen.width==800 && screen.height==600) {
		imagen='<img src="images/banner800_'+aleatorio+'.jpg" width="640">';
	} else if (screen.width==1024) {
		imagen='<img src="images/banner1024_'+aleatorio+'.jpg" width="860">';
	} else if(screen.width==1280) {
		imagen='<img src="images/banner1280_'+aleatorio+'.jpg" width="1120">';
	} else {
		imagen='<img src="images/banner1024_'+aleatorio+'.jpg" width="860">';
	}
	salir='<img src="../images/exit.png" width="129" height="129" alt="Salida Segura" title="Salida Segura">';
	document.write("<td colspan='2'><center><table><tr><td>"+imagen+"</td><td style='cursor: pointer;' onclick=\"location='../salir.php'\">"+
	salir+"</td></tr></table></center></td>");
}

function banner_close() {
	var aleatorio=Math.round(3*Math.random());
	if(aleatorio == 0 || aleatorio > 2) aleatorio=1;
	var imagen;
	if (screen.width==800 && screen.height==600) {
		imagen='<img src="images/banner800_'+aleatorio+'.jpg" width="640">';
	} else if (screen.width==1024) {
		imagen='<img src="images/banner1024_'+aleatorio+'.jpg" width="860">';
	} else if(screen.width==1280) {
		imagen='<img src="images/banner1280_'+aleatorio+'.jpg" width="1120">';
	} else {
		imagen='<img src="images/banner1024_'+aleatorio+'.jpg" width="860">';
	}
	salir='<img src="../images/salir_cerrar.png" width="129" height="129" alt="Cerrar" title="Cerrar">';
	document.write("<td colspan='2'><center><table><tr><td>"+imagen+"</td><td style='cursor: pointer;' onclick=\"window.close()\">"+
	salir+"</td></tr></table></center></td>");
}

function cargar(id_nv,order_by,id_ord_nv,tot,mensaje) {
	for (i=1;i<=tot;i++) {
		var man=document.getElementById(id_nv.substr(0,id_nv.lastIndexOf('_')+1)+i.toString() );
		if (id_nv == id_nv.substr(0,id_nv.lastIndexOf('_')+1) + i.toString()) {
			if (order_by == 'asc') {
				man.setAttribute("class", "encabezado_asc");
			}
			else {
				man.setAttribute("class", "encabezado_desc");
			}
			
			man.innerHTML='&nbsp;&nbsp;&nbsp;';
		} else {
			man.innerHTML='';
		}
	}
	
	man=document.getElementById(id_ord_nv);
	man.setAttribute("class","encabezado_ord");
	if (mensaje!='') mensaje_nv('ERROR',mensaje,Ext.MessageBox.OK,Ext.MessageBox.ERROR,'');
	//inicio();
}

/****FUNCIÓN PARA CARGAR DATOS EN UN DIV*/
function cargardatos (url) {
	//alert(url);
	var peticion=false;
	peticion=object();
	var element=document.getElementById('datos');
	element.innerHTML='<div id="proc_datos">Procesando Datos, Por Favor Espere...</div><img src="../images/progreso.gif">';
	var ancho=screen.width-110;
	var alto=screen.height-400;
	var atributo="overflow:auto; width: "+ancho.toString()+"px; height:  "+alto.toString()+"px;border: double; border-color: blue;";
	element.setAttribute("style",atributo);
	
	peticion.open("GET",url);
	peticion.onreadystatechange = function(){ 
			if (peticion.readyState == 4) {
			element.innerHTML = peticion.responseText;
			}
	}
	peticion.send(null);
	document.getElementById('argumentos').setAttribute("style", "display: none;");
}
function cargardatos1 (url) {
	//alert(url);
	var peticion=false;
	peticion=object();
	var element=document.getElementById('datos1');
	element.innerHTML='<div id="proc_datos">Procesando Datos, Por Favor Espere...</div><img src="../images/progreso.gif">';
	/*var ancho=screen.width-110;
	var alto=screen.height-400;
	var atributo="overflow:auto; width: "+ancho.toString()+"px; height:  "+alto.toString()+"px;border: double; border-color: blue;";
	element.setAttribute("style",atributo);*/
	
	peticion.open("GET",url);
	peticion.onreadystatechange = function(){ 
			if (peticion.readyState == 4) {
			element.innerHTML = peticion.responseText;
			}
	}
	peticion.send(null);
	document.getElementById('argumentos').setAttribute("style", "display: none;");
}

/*****FUNCION PARA MOSTRAR U OCULTAR ARGUMENTOS DE CONSULTA*/
function ver_argumento() {
	if (document.getElementById('argumentos').getAttribute("style")=="display: none;") {
		document.getElementById('argumentos').setAttribute("style","display: block;");
	} else {
		document.getElementById('argumentos').setAttribute("style","display: none;");
	}
}
/*****FUNCION PARA MOSTRAR U OCULTAR labels y submenus de busqueda de operador en Descuentos aplicados*/


 function mostrar_noms(id) {
	 if (document.getElementById(id).getAttribute("style")=="display: none;") {
			document.getElementById(id).setAttribute("style","display: block;");
		} else {
			document.getElementById(id).setAttribute("style","display: none;");
		}
}
 /*****FUNCION PARA MOSTRAR U OCULTAR labels y submenus de busqueda añadiendole el estilo*/


 function mostrar_noms_style(id,estilo) {
	if (document.getElementById(id).getAttribute("style")=="display: none;"+estilo) {
		document.getElementById(id).setAttribute("style","display: block;"+estilo);
	} else {
		document.getElementById(id).setAttribute("style","display: none;"+estilo);
	}
}
 /*****FUNCION PARA MOSTRAR U OCULTAR labels y submenus de busqueda de operador en Descuentos aplicados dependiendo de un id*/


 function mostrar_nomsid(id,valor) {
	 if(valor=='op5'){
	 if (document.getElementById(id).getAttribute("style")=="display: none;") {
			document.getElementById(id).setAttribute("style","display: block;");
		} else {
			document.getElementById(id).setAttribute("style","display: none;");
		}
	 }else{
		 if (document.getElementById(id).getAttribute("style")=="display: block;") {
				document.getElementById(id).setAttribute("style","display: none;");
			} else {
				document.getElementById(id).setAttribute("style","display: none;");
			}
	 }
}

/*****FUNCION PARA MOSTRAR U OCULTAR MENU*/
function ver_menu() {
	if (document.getElementById('menu_der').getAttribute("style")=="display: none;") {
		document.getElementById('menu_der').setAttribute("style","display: block;");
		document.getElementById('menu_izq').setAttribute("class","visible");
	} else {
		document.getElementById('menu_der').setAttribute("style","display: none;");
		document.getElementById('menu_izq').setAttribute("class","oculto");
	}
}

/****FUNCION PARA VALIDAR FECHA*/
function validar_fecha(fecha) {
	var fc=new Array();
	var hr=new Array();
	var fc_hora=new Array();
	fc_hora=fecha.split(' ');
	fc=fc_hora[0].split('/');
	if (fc_hora.length==2) hr=fc_hora[1].split(':');
	
	if (parseFloat(fc[2])<=0||parseFloat(fc[2])>9999) {
		mensaje_nv('ERROR','Año Invalido, Por Favor Verificar',Ext.MessageBox.OK,Ext.MessageBox.ERROR,'');
		return false;
	}
	
	if (parseFloat(fc[1])<=0||parseFloat(fc[1])>12) {
		mensaje_nv('ERROR','Mes Invalido, Por Favor Verificar',Ext.MessageBox.OK,Ext.MessageBox.ERROR,'');
		return false;
	}
	
	if (parseFloat(fc[0])<=0||parseFloat(fc[0])>31) {
		mensaje_nv('ERROR','Día Invalido, Por Favor Verificar',Ext.MessageBox.OK,Ext.MessageBox.ERROR,'');
		return false;
	}
	
	if (parseFloat(fc[1])==2) {
		if (parseFloat(fc[2])%4==0) {
			if (parseFloat(fc[0])>29) {
				mensaje_nv('ERROR','Día Invalido, Por Favor Verificar',Ext.MessageBox.OK,Ext.MessageBox.ERROR,'');
				return false;
			}
		} else {
			if (parseFloat(fc[0])>28) {
				mensaje_nv('ERROR','Día Invalido, Por Favor Verificar',Ext.MessageBox.OK,Ext.MessageBox.ERROR,'');
				return false;
			}
		}
	} else if (parseFloat(fc[1])==4||parseFloat(fc[1])==6||parseFloat(fc[1])==9||parseFloat(fc[1])==11) {
		if (parseInt(fc[0])>30) {
			mensaje_nv('ERROR','Día Invalido, Por Favor Verificar',Ext.MessageBox.OK,Ext.MessageBox.ERROR,'');
			return false;
		}
	}
	
	if (hr.length>0) {
		for (i=0;i<hr.length;i++) {
			switch (i) {
				case 0:
					if (parseInt(hr[0])<0||parseInt(hr[0])>23) {
						mensaje_nv('ERROR','Hora Invalida, Por Favor Verificar',Ext.MessageBox.OK,Ext.MessageBox.ERROR,'');
						return false;
					}
					break;
					
				case 1:
					if (parseInt(hr[1])<0||parseInt(hr[1])>59) {
						mensaje_nv('ERROR','Minuto Invalido, Por Favor Verificar',Ext.MessageBox.OK,Ext.MessageBox.ERROR,'');
						return false;
					}
					break;
					
				case 2:
					if (parseInt(hr[2])<0||parseInt(hr[2])>59) {
						mensaje_nv('ERROR','Segundo Invalido, Por Favor Verificar',Ext.MessageBox.OK,Ext.MessageBox.ERROR,'');
						return false;
					}
					break;
					
			}
		}
	}
	return true;
}

/****FUNCION PARA DAR FORMATO DE FECHA Y HORA DD/MM/AAAA HH:MM*/
function format_fec(campo,fl_hora) {
	var fc_hora=new Array();
	var fecha='';
	var hora='';
	
	if (campo.value != '') {
		fecha = campo.value.replace(/([^0-9])/g, '');
		hora = fecha.substr(8);
		fecha = fecha.substr(0, 8);
		
		fecha = fecha.substr(0, 2) + '/' + fecha.substr(2, 2) + '/' + fecha.substr(4, 4);
		
		switch (fl_hora) {
			case 'N':
				campo.value = fecha;
				break;
			case 'H':
				switch (hora.length) {
					case 0:
						hora = '00';
						break;
					case 1:
						hora = '0' + hora;
						break;
					default:
						hora = hora.substr(0, 2);
						break;
				}
				campo.value = fecha + ' ' + hora;
				break;
			case 'M':
				switch (hora.length) {
					case 0:
						hora = '00:00';
						break;
					case 1:
						hora = '0' + hora + ':00';
						break;
					case 2:
						hora += ':00';
						break;
					case 3:
						hora = hora.substr(0, 2) + ':0' + hora.substr(2);
						break;
					default:
						hora = hora.substr(0, 2) + ':' + hora.substr(2, 2);
						break;
				}
				campo.value = fecha + ' ' + hora;
				break;
			case 'S':
				switch (hora.length) {
					case 0:
						hora = '00:00:00';
						break;
					case 1:
						hora = '0' + hora + ':00:00';
						break;
					case 2:
						hora += ':00:00';
						break;
					case 3:
						hora = hora.substr(0, 2) + ':0' + hora.substr(2) + ':00';
						break;
					case 4:
						hora = hora.substr(0, 2) + ':' + hora.substr(2) + ':00';
						break;
					case 5:
						hora = hora.substr(0, 2) + ':' + hora.substr(2, 2) + ':0' + hora.substr(4);
						break;
					default:
						hora = hora.substr(0, 2) + ':' + hora.substr(2, 2) + ':' + hora.substr(4, 2);
						break;
				}
				campo.value = fecha + ' ' + hora;
				break;
		}
	}
}

/******FUNCION PARA CAMBIAR DE FORMATO LAS FECHAS 'DD/MM/YYYY' A 'YYYY-MM-DD'*/
function format_fc(fecha) {
	if (fecha!='') {
		var fc_hora = new Array();
		fc_hora=fecha.split(' ');
		fecha=fc_hora[0];
		var a_fecha = new Array();
		a_fecha=fecha.split('/');
		if (fc_hora.length==1) {
			return a_fecha[2]+'-'+a_fecha[1]+'-'+a_fecha[0];
		} else {
			return a_fecha[2]+'-'+a_fecha[1]+'-'+a_fecha[0]+' '+fc_hora[1];
		}
	} else {
		return '';
	}
}

/******FUNCION PARA CAMBIAR DE FORMATO LAS FECHAS 'YYYY-MM-DD' A 'DD/MM/YYYY'*/
function format_cf(fecha) {
	if (fecha!='') {
		var fc_hora = new Array();
		fc_hora=fecha.split(' ');
		fecha=fc_hora[0];
		var a_fecha = new Array();
		a_fecha=fecha.split('-');
		if (fc_hora.length==1) {
			return a_fecha[2]+'/'+a_fecha[1]+'/'+a_fecha[0];
		} else {
			return a_fecha[2]+'/'+a_fecha[1]+'/'+a_fecha[0]+' '+fc_hora[1];
		}
	} else {
		return '';
	}
}

/*****FUNCION PARA VALIDAR LONGITUD DE UN CAMPO*/
function valida_longitud(campo,longitud) {
	if (campo.value.length>longitud) {
		mensaje_nv('ERROR','..:: Longitud del Campo Excedio el Máximo Permitido que es '+ longitud + ' Caracteres ::..',Ext.MessageBox.OK,
		Ext.MessageBox.ERROR,'');
		foco(campo);
		return false;
	}
	return true;
}

/****FUNCION PARA COLOCAR CANTIDAD DE CARACTERES DIGITADOS*/
function cant_caracteres(campo,id,longitud) {
	document.getElementById(id).innerHTML='('+campo.value.length+'/'+longitud+')';
	if (campo.value.length>longitud) {
		document.getElementById(id).setAttribute("class","caract_mal");
	} else {
		document.getElementById(id).setAttribute("class","caract_bien");
	}
}
/***FUNCION PARA VALIDAR QUE SUBAN SOLO ARCHIVOS DE IMAGENES*/
function validar_foto(form) {
	archivo=form.f_imagen.value;
	
	extension=(archivo.substring(archivo.lastIndexOf("."))).toLowerCase();
	
	if(extension!='') {
		if(extension=='.jpg'||extension=='.JPG'||extension=='.gif'||extension=='.GIF'||extension=='.PNG'||extension=='.png'||
		extension=='.bmp'||extension=='.BMP'||extension=='.jpeg'||extension=='.JPEG') {
			return true;
		} else {
			mensaje_nv('ERROR','Archivo No Valido',Ext.MessageBox.OK,Ext.MessageBox.ERROR,'');
			return false;
		}
	}
	
	return true;
}
/****FUNCION PARA COMPLETAR EL NOMBRE*/
function com_nombres(t1,t2,t3,t4,campo) {
	var nombre='';
	nombre=t1;
	if (t2!='') nombre+=' '+t2;
	if (t3!='') nombre+=' '+t3;
	if (t4!='') nombre+=' '+t4;
	campo.value=nombre;
}
/**FUNCION PARA SERILIZAR VALORES COMO PHP*/
function serialize (mixed_value) {
	// http://kevin.vanzonneveld.net
	// +   original by: Arpad Ray (mailto:arpad@php.net)
	// +   improved by: Dino
	// +   bugfixed by: Andrej Pavlovic
	// +   bugfixed by: Garagoth
	// +      input by: DtTvB (http://dt.in.th/2008-09-16.string-length-in-bytes.html)
	// +   bugfixed by: Russell Walker (http://www.nbill.co.uk/)
	// +   bugfixed by: Jamie Beck (http://www.terabit.ca/)
	// %          note: We feel the main purpose of this function should be to ease the transport of data between php & js
	// %          note: Aiming for PHP-compatibility, we have to translate objects to arrays
	// *     example 1: serialize(['Kevin', 'van', 'Zonneveld']);
	// *     returns 1: 'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'
	// *     example 2: serialize({firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'});
	// *     returns 2: 'a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}'
	
	var _getType = function (inp) {
		var type = typeof inp, match;
		var key;
		if (type == 'object' && !inp) {
			return 'null';
		}
		
		if (type == "object") {
			if (!inp.constructor) {
				return 'object';
			}
			var cons = inp.constructor.toString();
			match = cons.match(/(\w+)\(/);
			if (match) {
				cons = match[1].toLowerCase();
			}
			var types = ["boolean", "number", "string", "array"];
			for (key in types) {
				if (cons == types[key]) {
					type = types[key];
					break;
				}
			}
		}
		return type;
	};
	var type = _getType(mixed_value);
	var val, ktype = '';
	
	switch (type) {
		case "function":
			val = "";
			break;
		case "boolean":
			val = "b:" + (mixed_value ? "1" : "0");
			break;
		case "number":
			val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
			break;
		case "string":
			val = "s:" + encodeURIComponent(mixed_value).replace(/%../g, 'x').length + ":\"" + mixed_value + "\"";
			break;
		case "array":
		case "object":
			val = "a";
			/*
				if (type == "object") {
					var objname = mixed_value.constructor.toString().match(/(\w+)\(\)/);
					if (objname == undefined) {
						return;
					}
					objname[1] = this.serialize(objname[1]);
					val = "O" + objname[1].substring(1, objname[1].length - 1);
				}
			*/
			var count = 0;
			var vals = "";
			var okey;
			var key;
			for (key in mixed_value) {
				ktype = _getType(mixed_value[key]);
				if (ktype == "function") {
					continue;
				}
				okey = (key.match(/^[0-9]+$/) ? parseInt(key, 10) : key);
				vals += this.serialize(okey) +this.serialize(mixed_value[key]);
				count++;
			}
			val += ":" + count + ":{" + vals + "}";
			break;
		case "undefined": // Fall-through
		default: // if the JS object has a property which contains a null value, the string cannot be unserialized by PHP
			val = "N";
			break;
	}
	if (type != "object" && type != "array") {
		val += ";";
	}
	return val;
}
/**DESERIALIZAR VALORES COMO PHP*/
function unserialize (data) {
	// http://kevin.vanzonneveld.net
	// +     original by: Arpad Ray (mailto:arpad@php.net)
	// +     improved by: Pedro Tainha (http://www.pedrotainha.com)
	// +     bugfixed by: dptr1988
	// +      revised by: d3x
	// +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +        input by: Brett Zamir (http://brett-zamir.me)
	// +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +     improved by: Chris
	// +     improved by: James
	// %            note: We feel the main purpose of this function should be to ease the transport of data between php & js
	// %            note: Aiming for PHP-compatibility, we have to translate objects to arrays
	// *       example 1: unserialize('a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}');
	// *       returns 1: ['Kevin', 'van', 'Zonneveld']
	// *       example 2: unserialize('a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}');
	// *       returns 2: {firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'}
	
	var error =	function (type, msg, filename, line){
								throw new this.window[type](msg, filename, line);
							};
	var read_until=	function (data, offset, stopchr){
										var buf = [];
										var chr = data.slice(offset, offset + 1);
										var i = 2;
										while (chr != stopchr) {
											if ((i+offset) > data.length) {
												error('Error', 'Invalid');
											}
											buf.push(chr);
											chr = data.slice(offset + (i - 1),offset + i);
											i += 1;
										}
										return [buf.length, buf.join('')];
									};
	var read_chrs =	function (data, offset, length){
										var buf;
										
										buf = [];
										for (var i = 0;i < length;i++){
											var chr = data.slice(offset + (i - 1),offset + i);
											buf.push(chr);
										}
										return [buf.length, buf.join('')];
									};
	var _unserialize =	function (data, offset){
												var readdata;
												var readData;
												var chrs = 0;
												var ccount;
												var stringlength;
												var keyandchrs;
												var keys;
												if (!offset) {
													offset = 0;
												}
												var dtype = (data.slice(offset, offset + 1)).toLowerCase();
												
												var dataoffset = offset + 2;
												var typeconvert = new Function('x', 'return x');
												
												switch (dtype){
													case 'i':
														typeconvert =	function (x) {
																						return parseInt(x, 10);
																					};
														readData = read_until(data, dataoffset, ';');
														chrs = readData[0];
														readdata = readData[1];
														dataoffset += chrs + 1;
														break;
													case 'b':
														typeconvert =	function (x) {
																						return parseInt(x, 10) !== 0;
																					};
														readData = read_until(data, dataoffset, ';');
														chrs = readData[0];
														readdata = readData[1];
														dataoffset += chrs + 1;
														break;
													case 'd':
														typeconvert =	function (x) {
																						return parseFloat(x);
																					};
														readData = read_until(data, dataoffset, ';');
														chrs = readData[0];
														readdata = readData[1];
														dataoffset += chrs + 1;
														break;
													case 'n':
														readdata = null;
														break;
													case 's':
														ccount = read_until(data, dataoffset, ':');
														chrs = ccount[0];
														stringlength = ccount[1];
														dataoffset += chrs + 2;
														
														readData = read_chrs(data, dataoffset+1, parseInt(stringlength, 10));
														chrs = readData[0];
														readdata = readData[1];
														dataoffset += chrs + 2;
														if (chrs != parseInt(stringlength, 10) && chrs != readdata.length){
															error('SyntaxError', 'String length mismatch');
														}
														break;
													case 'a':
														readdata = {};
														
														keyandchrs = read_until(data, dataoffset, ':');
														chrs = keyandchrs[0];
														keys = keyandchrs[1];
														dataoffset += chrs + 2;
														
														for (var i = 0; i < parseInt(keys, 10); i++){
															var kprops = _unserialize(data, dataoffset);
															var kchrs = kprops[1];
															var key = kprops[2];
															dataoffset += kchrs;
															
															var vprops = _unserialize(data, dataoffset);
															var vchrs = vprops[1];
															var value = vprops[2];
															dataoffset += vchrs;
															
															readdata[key] = value;
														}
														
														dataoffset += 1;
														break;
													default:
														error('SyntaxError', 'Unknown / Unhandled data type(s): ' + dtype);
														break;
												}
												return [dtype, dataoffset - offset, typeconvert(readdata)];
											};
											
	return _unserialize((data+''), 0)[2];
}
/**REDONDEAR UN VALOR A UNA CANTIDAD DE DECIMALES*/
function redondear(cantidad, decimales) {
	var cantidad = parseFloat(cantidad);
	var decimales = parseFloat(decimales);
	decimales = (!decimales ? 2 : decimales);
	return Math.round(cantidad * Math.pow(10, decimales)) / Math.pow(10, decimales);0
}
/** codigo generado para eliminar filas de una tabla*/
function eliminar_fila(id_tabla,id_fila) {
	var fila=document.getElementById(id_fila);
	var tabla=document.getElementById(id_tabla);
	//alert(fila);
	tabla.removeChild(fila); // REMUEVE LA FILA
}
/** funcion cambiar valor de boton*/
function cmvalue2()
{
  var btn2 = document.getElementById("btn2");
  if(btn2.value == "+") {
    btn2.value = "-";
    btn2.innerHTML="-";
   
  } else {
    btn2.value = "+";
    btn2.innerHTML="+";
 }
}

function cmvalue()
{
  var btn = document.getElementById("btn");
  if(btn.value == "+") {
    btn.value = "-";
    btn.innerHTML="-";
  } else {
    btn.value = "+";
    btn.innerHTML="+";
  }
}
/**MOSTRAR EN UNA CAPA DETALLE DEL NIT SELECCIONADO*/
function detalle_nit (nit,e) {
		var ok=true;
		var peticion = false;
		peticion=object();
		/** UBICACION DE LA CAPA*/
		var y=e.clientY;
		var div=document.getElementById('DivMover');
		div.style.left='10%';
		div.style.visibility= "visible";
		
		var url='../includes/graf_dir_detallado.php?documento='+nit;
		peticion.open("GET",url);
		peticion.onreadystatechange=function(){
																						if (peticion.readyState==4) {
																							div.innerHTML=peticion.responseText;
																						}
																					}
		peticion.send(null);
		document.getElementById('opaco').setAttribute("style","opacity: 0.5");
}
/**HACER VISIBLE O NO UNA CAPA*/
function capa(accion,elemento) {
	//alert("Por aqui");
	var div=document.getElementById(elemento);
	if (accion == '1') {
		div.style.visibility = "visible";
		document.getElementById('opaco').setAttribute("style","opacity: 0.5");
	} else {
		div.style.visibility = "hidden";
		document.getElementById('opaco').setAttribute("style","opacity: ");
		
	}
}
/**MOSTRAR EN UNA CAPA DETALLE DEL NIT SELECCIONADO*/
function fecha_actual () {
		var ok=true;
		var peticion=false;
		var datos=new Array();
		peticion=object();
		/** UBICACION DE LA CAPA*/
		
		var url='../includes/fecha_actual.php';
		peticion.open("GET",url);
		peticion.onreadystatechange=function(){
																						if (peticion.readyState==4) {
																							datos=peticion.responseText.split('-');
																							var fecha=new Date(datos[0],datos[1],datos[2],datos[3],datos[4],datos[5]);
																							alert(fecha);
																							return fecha;
																						}
																					}
		peticion.send(null);
}
/**MOSTRAR CONSULTA AVANZADA*/
function mostrar_fc(id_tabla,boton) {
	if (document.getElementById(id_tabla).style.display=="none") {
		document.getElementById(id_tabla).style.display="block";
	} else {
		document.getElementById(id_tabla).style.display="none";
	}
	
	if (boton.value=='+') {
		boton.value='-';
	} else {
		boton.value='+';
	}
	
}
/**CAMBIAR NOMBRE A CAMPO DE FECHA*/
function nm_fecha(campo,id_fecha,nm_campo,id_t_hasta,id_fc_hasta,id_tabla,boton,t_hasta) {
	document.getElementById(id_fecha).innerHTML=nm_campo+campo.id;
	if (campo.value!='7') {
		document.getElementById(id_t_hasta).style.visibility="collapse";
		document.getElementById(id_fc_hasta).style.visibility="collapse";
		t_hasta.value='';
	} else {
		document.getElementById(id_t_hasta).style.visibility="visible";
		document.getElementById(id_fc_hasta).style.visibility="visible";
	}
	
	mostrar_fc(id_tabla,boton);
}
function veh_placa(dato,campo) {
	var peticion=false;
	peticion=object();
	var fragment_url='../includes/veh_placa.php?veh_placa='+dato+'&'+param();
	//abrimos la url
	peticion.open("GET",fragment_url); 
	peticion.onreadystatechange=function(){ 
																					if (peticion.readyState==4) {
																						campo.value=peticion.responseText;
																					}
																				}
	peticion.send(null);
}
/**MANEJO DE PESTAÑAS EN LOS FORMULARIO**/
function ver_pesta(tot,no_id,id_pes,id_tab) {
	document.getElementById(id_pes+id_actual.toString()).setAttribute("class","actual");
	document.getElementById(id_tab+id_actual.toString()).style.display='block';
	for (var i=0;i<=tot;i++) {
		if (i!=id_actual) {
			document.getElementById(id_pes+i.toString()).setAttribute("class","boton_pes");
			document.getElementById(id_tab+i.toString()).style.display='none';
		}
	}
}
