/*******************************************************************/
/***   recopilado por luisfel  (luisfel@luisfel.cl) 03/2004      ***/
/*******************************************************************/

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 MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' debe contener un email válido.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' debe contener sólo números.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' debe contener un número entre '+min+' y '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' es necesario.\n'; }
  } if (errors) alert('Los siguientes problemas han sido encontrados:\n'+errors);
  document.MM_returnValue = (errors == '');
}


function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

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 MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}

function MM_popupMsg(msg) { //v1.0
  alert(msg);
}

function MM_openBrWindowunder(theURL,winName,features) { //v2.0 (LF)
  window.open(theURL,winName,features);
  window.focus();
}
function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_controlShockwave(objStr,x,cmdName,frameNum) { //v3.0
  var obj=MM_findObj(objStr);
  if (obj) eval('obj.'+cmdName+'('+((cmdName=='GotoFrame')?frameNum:'')+')');
}

function mostrar(elid) {
	var obj=MM_findObj(elid);
	if(obj.style.display=="none"){
	obj.style.display="";
	} else {
	obj.style.display="none";
	}
}

function putFocus(campo) {
	try{
		var elcampo=MM_findObj(campo);
		elcampo.focus();
	}catch(e){}
}
 
 function nuevoAjax(){
	var xmlhttp=false;
	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (E) {
					try{
						xmlhttp = new XMLHttpRequest();
					} catch(E2){
						xmlhttp = false;
					}
			}
	}
	
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
	xmlhttp = new XMLHttpRequest();
	}
	return xmlhttp;
}

// Función que deja deshabilitado los campos de un formulario
// excepto el elemento que se pase como 2do parametro.
// recibe el nombre del formulario que se quiere deshabilitar
// y el nombre del elemento excepción
// Cristian.
function deshabilitar_form(formulario, excepcion){
	var form = MM_findObj(formulario);
	for (i = 0; i < form.length; i++){
		if (form.elements[i].name != excepcion){
			try{
				form.elements[i].disabled = true
			}catch(e){}
		}
	}
}

// Funcion que habilita los elementos del formulario y cambia
// el comportamiento del boton para que haga submit al formulario
// Recibe el nombre del formulario, el nombre del boton que hara el submit
// y el <?php echo $i_Nuevo ?> value que tendrá dicho boton.
// Cristian MODIF: como tiene problemas para usar el MM_validateForm(), 
// se cambia y se usa un boton submit oculto
function habilitar_form(formulario, bot_oculto, bot_saliente){
	var bot = MM_findObj(bot_oculto);
	var form = MM_findObj(formulario);
	for (i = 0; i < form.length; i++){
		try{
			form.elements[i].disabled = false
		}catch(e){}
	}
	bot_saliente.style.display = 'none';
	bot.style.display = '';
}

function comparaClaves(clave1, clave2){
	if(clave1.value != clave2.value){
		alert('Las claves no coinciden. Deben ser iguales!');
		putFocus(clave1);
		return false;
	}else return true;
}

function number_format(a, b, c, d) {
 a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
 e = a + '';
 f = e.split('.');
 if (!f[0]) {
  f[0] = '0';
 }
 if (!f[1]) {
  f[1] = '';
 }
 if (f[1].length < b) {
  g = f[1];
  for (i=f[1].length + 1; i <= b; i++) {
   g += '0';
  }
  f[1] = g;
 }
 if(d != '' && f[0].length > 3) {
  h = f[0];
  f[0] = '';
  for(j = 3; j < h.length; j+=3) {
   i = h.slice(h.length - j, h.length - j + 3);
   f[0] = d + i +  f[0] + '';
  }
  j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
  f[0] = j + f[0];
 }
 c = (b <= 0) ? '' : c;
 return f[0] + c + f[1];
}

function limpiaMuestraForm(eldiv, elform){
	// primero vemos si el formulario esta oculto, para mostrarlo
	var el_div = MM_findObj(eldiv);
	try{ el_div.style.display = '';}catch(e){alert(e.message)}
	
	// ahora limpiamos el formulario
	var form = MM_findObj(elform);
	for(i=0; i<form.length; i++){
		try{
			if(form.elements[i].type == 'text')form.elements[i].value = '';
			if(form.elements[i].type == 'hidden')form.elements[i].value = '';
			if(form.elements[i].type == 'password')form.elements[i].value = '';
			if(form.elements[i].type == 'textarea')form.elements[i].value = '';
			if(form.elements[i].type == 'checkbox')form.elements[i].checked = false;
			if(form.elements[i].type == 'radio')form.elements[i].selected = false;
			if(form.elements[i].type == 'select-one')form.elements[i].selectedIndex = 0;
		}catch(e){alert(e.message)}
	}
	// ahora saltamos hacia el anchor... como inicialmente esta función
	// no tenia esta opción, lo dejamos como parámetro optativo
	if(limpiaMuestraForm.arguments[2] !=null)document.location.href='#'+limpiaMuestraForm.arguments[2];
}

function cuentapalabras(obj, maxim){
	if(obj.value.length >= maxim){
			obj.value =  obj.value.substr(0, (obj.value.length-1));
			obj.blur()
			alert('Ha sobrepasado el límite máximo permitido');
			return false;
	}else return true;
}

function i_agree(objChbox, btn){
	var bt = MM_findObj(btn);
	if(objChbox.checked==true){
		bt.disabled = false;
		return true;
	} else {
		bt.disabled = true;
		return false;
	}
}


/*
Funcion para cargar datos en campos select dependientes. Por ejemplo, si hay un select con paises, 
esta funcion permite cargar en otro select las ciudades de este pais
Recibe como parametro 
- El nombre del campo select donde se quieren cargar datos, 
- Un array con la infomación para cargar el campo, enformato 
	array[] = 'id_pais|id_ciudad|nom_ciudad';
- ID maestro para la búsqueda (para el ejemplo, sería id_pais)
*/
function cargaSelectDependiente(cmp_sel, arr_data, id_key){
	// primero, limpiamos el select
	var campo_sel = MM_findObj(cmp_sel);
	for(i=0;i<campo_sel.length;i++){
		campo_sel.options[i] = null
	}
	// ahora, sacamos las partes del array, y filtramos segun id_key
	var arr_aux = new Array();// Arreglo auxiliar para meter los conces
	var j = 0;
	for(i=0;i<arr_data.length;i++){
		var partes = arr_data[i].split('|');
		if(partes[0] == id_key){     // Filtraje id_key
			arr_aux[j++] = partes[1]+'|'+partes[2];
		}
	}
	// y ya que tenemos los datos filtrados, los metemos en el campo select
	campo_sel.options[0] = new Option('Seleccione', '');
	for(i=0;i<arr_aux.length;i++){
		var p = arr_aux[i].split('|');
		campo_sel.options[i+1] = new Option(p[1], p[0]);
	}
}


/*
* Función que solo permite meter numeros en un campo de texto, colocando el código:
  onkeypress="return isNumberKey(event)"
*/
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
	return false;

return true;
}

function limpiaSelect(sel){
	var sele = MM_findObj(sel);
	for(i=0; i<=sele.length; i++){
		sele.options[i] = null;
	}
}

function limpiaTabla(tbody){
	var tableBody = MM_findObj(tbody);
	while(tableBody.childNodes.length > 0) { tableBody.removeChild(tableBody.childNodes[0]); } 
}
function celdaTXT(txt){
	var cel = document.createElement('td');
	cel.appendChild(document.createTextNode(txt));
	return cel;
}
function celdaHTML(txt){
	var cel = document.createElement('td');
	cel.innerHTML = txt;
	return cel;
}

/* Función que limpia el formato del codigo de barra y retorna sólo el id del producto
Debe eliminar la fecha (1eros 8 digitos) y el DV del final, 
y el Nº resultante lo debe retornar sin ceros a la izquierda*/
function limpiaCod(cod){
	if(cod=='')return '';//Para que no retorne cero
	var snFec = cod.substr(8);//Cortamos desde el 8vo car. para eliminar fecha
	var snDv = snFec.substr(0,snFec.length-1);//Sacamos DV
	// Para elejir si mando la cifra con los ceros o parseada(que no funca mucho la verdad...)
	return (limpiaCod.arguments[1]=='1'?snDv:parseInt(snDv));	
}

// Funciones para poder modificar ivas y totales
function recTot(tot){
	tot = (!isNaN(tot)?tot:0);
	MM_findObj('subtotal').value = tot;
	MM_findObj('iva').value = Math.round(tot*0.19);
	MM_findObj('total').value = Math.round(tot*1.19);
}

function recIva(){
	MM_findObj('total').value = parseInt(MM_findObj('iva').value) + parseInt(MM_findObj('subtotal').value);
}

// Funcion para confirmar eliminacion de un registro. Si no se especifica la página donde se elimina el registro, toma la actual
function confElim(id, pag){
	var conf = confirm('Está seguro que desea eliminar este registro? esta acción no se puede deshacer');
	if(conf)window.location=(pag!=undefined?pag:'')+'?id_elm='+id;
}

