// JavaScript Document


/* Section: Core Functions */

// This function formats numbers by adding commas
function numberFormat(nStr){
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1))
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  return x1 + x2;
}

// This function removes non-numeric characters
function stripNonNumeric( str ){
  str += '';
  var rgx = /^\d|\.|-$/;
  var out = '';
  for( var i = 0; i < str.length; i++ ){
    if( rgx.test( str.charAt(i) ) ){
      if( !( ( str.charAt(i) == '.' && out.indexOf( '.' ) != -1 ) ||
             ( str.charAt(i) == '-' && out.length != 0 ) ) ){
        out += str.charAt(i);
      }
    }
  }
  return out;
}

/*
Function: $defined
	Returns true if the passed in value/object is defined, that means is not null or undefined.

Arguments:
	obj - object to inspect
*/

function $defined(obj){
	return (obj != undefined);
};

/*
Function: $type
	Returns the type of object that matches the element passed in.

Arguments:
	obj - the object to inspect.

Example:
	>var myString = 'hello';
	>$type(myString); //returns “string”

Returns:
	'element' - if obj is a DOM element node
	'textnode' - if obj is a DOM text node
	'whitespace' - if obj is a DOM whitespace node
	'arguments' - if obj is an arguments object
	'object' - if obj is an object
	'string' - if obj is a string
	'number' - if obj is a number
	'boolean' - if obj is a boolean
	'function' - if obj is a function
	'regexp' - if obj is a regular expression
	'class' - if obj is a Class. (created with new Class, or the extend of another class).
	'collection' - if obj is a native htmlelements collection, such as childNodes, getElementsByTagName .. etc.
	false - (boolean) if the object is not defined or none of the above.
*/

function $type(obj){
	if (!$defined(obj)) return false;
	if (obj.htmlElement) return 'element';
	var type = typeof obj;
	if (type == 'object' && obj.nodeName){
		switch(obj.nodeType){
			case 1: return 'element';
			case 3: return (/S/).test(obj.nodeValue) ? 'textnode' : 'whitespace';
		}
	}
	if (type == 'object' || type == 'function'){
		switch(obj.constructor){
			case Array: return 'array';
			case RegExp: return 'regexp';
			case Class: return 'class';
		}
		if (typeof obj.length == 'number'){
			if (obj.item) return 'collection';
			if (obj.callee) return 'arguments';
		}
	}
	return type;
};

function isType(o, type) {
return type == $type(o);
}

function isTYPE(o) {
	return (o != null && typeof o == 'object' && o.constructor.toString() == TYPE.toString());
}

/**
 * Formats the number according to the 'format' string; adherses to the american number standard where a comma is inserted after every 3 digits.
 *  note: there should be only 1 contiguous number in the format, where a number consists of digits, period, and commas
 *        any other characters can be wrapped around this number, including '$', '%', or text
 *        examples (123456.789):
 *          '0′ - (123456) show only digits, no precision
 *          '0.00′ - (123456.78) show only digits, 2 precision
 *          '0.0000′ - (123456.7890) show only digits, 4 precision
 *          '0,000′ - (123,456) show comma and digits, no precision
 *          '0,000.00′ - (123,456.78) show comma and digits, 2 precision
 *          '0,0.00′ - (123,456.78) shortcut method, show comma and digits, 2 precision
 *
 * @method format
 * @param format {string} the way you would like to format this text
 * @return {string} the formatted number
 * @public
 */
Number.prototype.format = function(format) {
	if (! isType(format, 'string')) {return '';} // sanity check

	var hasComma = -1 < format.indexOf(','),
		psplit = format.stripNonNumeric().split('.'),
		that = this;

//    alert("hasComma = " + hasComma);

    // compute precision
	if (1 < psplit.length) {
		// fix number precision
//        alert("psplit[1].length = " + psplit[1].length);
        that = that.toFixed(psplit[1].length);
//        alert("that = " + that);
    }
	// error: too many periods
	else if (2 < psplit.length) {
		throw('NumberFormatException: invalid format, formats should have no more than 1 period: ' + format);
	}
	// remove precision
	else {
		that = that.toFixed(0);
	}

	// get the string now that precision is correct
	var fnum = that.toString();

//    alert("fnum = " + fnum);

    // format has comma, then compute commas
	if (hasComma) {
		// remove precision for computation
		psplit = fnum.split('.');

		var cnum = psplit[0],
			parr = [],
			j = cnum.length,
			m = Math.floor(j / 3),
			n = cnum.length % 3 || 3; // n cannot be ZERO or causes infinite loop

		// break the number into chunks of 3 digits; first chunk may be less than 3
		for (var i = 0; i < j; i += n) {
			if (i != 0) {n = 3;}
			parr[parr.length] = cnum.substr(i, n);
			m -= 1;
		}

		// put chunks back together, separated by comma
		fnum = parr.join(',');

		// add the precision back in
		if (psplit[1]) {fnum += '.' + psplit[1];}
	}
//        alert("fnum = " + fnum);
                         
	// replace the number portion of the format with fnum
//    var tempo = format.replace(/[d,?.?]+/, fnum);
//    alert("tempo = " + tempo);
    return fnum;
};

String.prototype.stripNonNumeric = function(){
    return this.remove(/[^0-9\-\.]/g);
//    return this;
}

String.prototype.remove = function(rx) {
		return this.replace(rx, '');
}


    function empieza(){
		//history.forward(null);
		history.go(1);
	} 
// Apaga un elemento del Formulario
	function dis(forma,elem){
		empieza();
		document [forma][elem].disabled = true;
	}
	
	function dis2(forma1,elem1,forma2,elem2){
		empieza();
		if (document [forma1] [elem1].value==""){
			document [forma2] [elem2].disabled = true;
		}		
	}
	
	function ena(forma,elem){
		document [forma][elem].disabled = false;
	}

    function holaMundo() {
        var x = 7;
        var y = 9;
        if (x == 8) {
            y = 1;
        } else {
            y = 2;
        }
    }

    function computePer(form,elem) {
        cantidad=eval(form.cantidad.value);
        valorBase=eval(form.valorBase.value);
        dedicacion = eval(eval(form.dedicacion.value)/100);        

        tiempo=eval(form.tiempo.value)
        valorMes=eval(form.valorMes.value)
        valorTotal=eval(form.valorTotal.value)

        with (Math) {
            mes = round(cantidad * valorBase * dedicacion * 100) /100;
            total = round( mes * tiempo * 100 ) /100;
        }
        form.valorMes.value = mes;
        form.valorTotal.value = total;

		form [elem].disabled = false;
    }
	
	function computeInd(form,elem) {
        cantidad=eval(form.cantidad.value)
        valorBase=eval(form.valorBase.value)
        tiempo=eval(form.tiempo.value)
        with (Math) {
          mes = cantidad * valorBase;
          total = mes * tiempo;
        }
        form.valorMes.value = mes;
        form.valorTotal.value = total;
		form [elem].disabled = false;
    }
	
	function agale (form){
        var value = form.empleado.value;
		var desde = value.indexOf("&");
		var subcadena1 = value.substring(desde+1);
		form.valorBase.value = subcadena1;
    }


    function enviarSiEsFamiliar(forma, requ, tipoPlan){
        //alert("enviara");
        var tip = forma[tipoPlan].value;
//        alert("tip = " + tip);
        if(tip == 3){
            forma.tipo.value = requ;
            forma.submit();
        }
//        else{
//            forma.tipo.value = infoplan;
//            forma.submit();
//        }


    }

    function esLAFamiliar(forma, requ, tipoPlan){
        var tip = forma[tipoPlan].value;
        if(tip == 3){
            return true;
        }
    }

    function enviar(forma, requ){
        //alert("enviara");
//        alert("forma = " + forma);
        forma.tipo.value = requ;
        forma.submit();
    }

    function enviarReciboCaja(forma, requ, nrr){
        //alert("enviara");
//        alert("forma = " + forma);
        forma.tipo.value = requ;
        forma.nr.value = nrr;
        forma.submit();
    }

    function enviarConfirma(forma, requ, mensaje){
//        alert("enviara");
//        alert("forma = " + forma);
        args=enviarConfirma.arguments;
//        alert("args.length = " + args.length);
        var elemAux;
        var nombre;
        for(i=3; i<args.length; i++){
            nombre = "p"+(i-3);
//            alert("nombre = " + nombre);
            elemAux = forma[nombre];
//            alert("elemAux = " + elemAux);
            elemAux.value = args[i];
        }
        forma.tipo.value = requ;
        if(confirm(mensaje)){
            forma.submit();
        }
    }
    
    //por favor no me borre
    
    function enviarNuevaVentana(forma, requ){
        forma.target = "b"+Math.random();
        forma.tipo.value = requ;
        forma.submit();
        forma.target = "";
    }

    function enviarNuevaVentanaDisabled(forma,tipo,botonAApagar){
        forma.target = "b"+Math.random();
        var boOFF = forma[botonAApagar];
        boOFF.disabled = true;
        boOFF.style.visibility = 'hidden';
        forma.tipo.value = tipo;
        forma.submit();
        forma.target = "";
    }
    function enviarNuevaVentanaDisabled2(forma,tipo,botonAApagar,botonAencender){
        forma.target = "b"+Math.random();
        forma[botonAApagar].disabled = true;
        forma[botonAencender].disabled = false;
        forma.tipo.value = tipo;
        forma.submit();
        forma.target = "";
    }

    function menuPropuesta(form){
		var value = form.idPropuesta.value;
		var indice1 = value.indexOf(",");
		var indice2 = value.indexOf(";");
		var indice3 = value.indexOf(":");
		var subcadena1 = value.substring(0,indice1);
		var subcadena2 = value.substring(indice1+1,indice2);
		form.categoria.value = subcadena2;
    	var subcadena3 = value.substring(indice2+1,indice3);
		var subcadena4 = value.substring(indice3+1);
		form.titulo.value = subcadena3;
		form.fecha.value = subcadena4;
        form.cargarPropuesta.disabled = false;
	}

    function seleccionaTodo(forma,elemento1){
        elemento1 = 'checkfacturas';
        //elemento1 = 'bfacturar';
        //alert("elemento1 " + forma[elemento1]);
        //forma[elemento1].disabled = !forma[elemento1].disabled;
        forma[elemento1].checked = !forma[elemento1].checked;
    }
	function activaDesactiva(forma,elemento1){
	    forma[elemento1].disabled = !forma[elemento1].disabled;
	}

	function ActivaOpcionOtro(forma,elemento1,elemento2){
	    forma[elemento1].disabled = !forma[elemento1].disabled;
	    forma[elemento2].disabled = !forma[elemento2].disabled;
	    if(forma[elemento2].disabled){
	        forma[elemento2].value = 'use para nuevo valor';
	    } else {
	        forma[elemento2].value = '';
	        forma[elemento2].focus();
	        forma[elemento2].select();
	    }
	}
	function ActivaOpcionBorrar(forma,elemento1){
	    forma[elemento1].disabled = !forma[elemento1].disabled;
	}

    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;
    }

//    este casi no se usa
    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 una direcci�n de eMail.\n';
          } else if (test!='R') { num = parseFloat(val);
            if (isNaN(val)) errors+='- '+nm+' debe contener un numero.\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 numero entre '+min+' y '+max+'.\n';
        } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
      } if (errors) alert('El siguiente error(es) ocurrieron:\n'+errors);
      document.MM_returnValue = (errors == '');
    }

    function MM_validateForm2NuevaVentana() { //v4.0
    //alert("hola mperro");
        var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm2NuevaVentana.arguments;
        for (i=2; 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 una direccion de eMail.\n';
                    } else
                        if (test!='R') {
                        num = parseFloat(val);
                        if (isNaN(val))
                            errors+='- '+nm+' debe contener un numero.\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 numero entre '+min+' y '+max+'.\n';
                        }
                    }
                } else
                    if (test.charAt(0) == 'R')
                        errors += '- '+nm+' es obligatorio.\n';
            }
        }
        if (errors)
            alert('El siguiente error(es) ocurrieron:\n'+errors);
        else {
            //alert('No hubo errores');
            var forma = args[0];
            //forma [args[1]].disabled = false;
            forma.target = "b"+Math.random();
            forma.tipo.value = args[1];
            //alert('tipo: ' + forma.tipo.value);
            forma.submit();
            forma.target = "";
        }
        document.MM_returnValue = (errors == '');
    }

    function MM_validateForm2Confirma() { //v4.0
    //alert("hola mperro");
        var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm2Confirma.arguments;

        // validar tarifa, sobre importante cruceros
        var f = args[0];
        var tarifausd = f.tarifausd;
        tarifausd = eval(tarifausd.value);
//        alert("tarifausd = " + tarifausd);

        if(tarifausd == 0){
            errors += '- la tarifa esta en cero o no definida. \n';
        }

        if(tarifausd == 0){
//            errors += '- la tarifa esta en cero o no definida. \n';
        }

        if(tarifausd < 0){
            errors += '- la tarifa es negativa. \n';
        }

        for (i=2; 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 una direccion de eMail.\n';
                    } else
                        if (test!='R') {
                        num = parseFloat(val);
                        if (isNaN(val))
                            errors+='- '+nm+' debe contener un numero.\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 numero entre '+min+' y '+max+'.\n';
                        }
                    }
                }else
                    if (test.charAt(0) == 'R')
                        errors += '- '+nm+' es obligatorio.\n';
            }
        }
        if (errors)
            alert('El siguiente error(es) ocurrieron:\n'+errors);
        else {
            //alert('No hubo errores');
            var forma = args[0];
            //forma [args[1]].disabled = false;
            forma.tipo.value = args[1];
            //alert('tipo: ' + forma.tipo.value);
            if(confirm("La presente tarjeta comienza proceso de facturacion y cobro respectivo, desea continuar?")){
                forma.submit();
            }
        }
        document.MM_returnValue = (errors == '');
    }


    function MM_validateForm2() { //v4.0
//    alert("hola mperro");
        var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm2.arguments;
        for (i=2; i<(args.length-2); i+=3) {
            test=args[i+2]; val=MM_findObj(args[i]);
            if (val) {
                nm=args[i+1];
            	if(nm == ''){
	                nm=args[i];
            	}
                val=val.value;
                //alert('val ' + val);
                if (val == '%' && test.charAt(0) == 'R'){
                	errors += '- '+nm+' es obligatorio.\n';
                }

                if (val!="") {
                        //alert('aki');
                    if (test.indexOf('isEmail')!=-1) {
                        p=val.indexOf('@');
                        if (p<1 || p==(val.length-1)) errors+='- '+nm+' debe contener una direccion de eMail.\n';
                    } else
                        if (test!='R') {
                        num = parseFloat(val);
                        if (isNaN(val))
                            errors+='- '+nm+' debe contener un numero.\n';
                        //alert (test.indexOf('inRange'));
                        if (test.indexOf('inRange') != -1) {
                            p=test.indexOf(':');
                            //alert(p);
                            min=test.substring(8,p);
                            max=test.substring(p+1);
                            if (num<min || max<num)
                                errors+='- '+nm+' debe contener un numero entre '+min+' y '+max+'.\n';
                        }
                    }
                } else
                    if (test.charAt(0) == 'R'
                    || test.indexOf('inRange')!=-1
                    || test.indexOf('isEmail')!=-1)
                        errors += '- '+nm+' es obligatorio.\n';

            }
        }
        if (errors)
            alert('El siguiente error(es) ocurrieron:\n'+errors);
        else {
            //alert('No hubo errores');
            var forma = args[0];
            //forma [args[1]].disabled = false;
            forma.tipo.value = args[1];
            //alert('tipo: ' + forma.tipo.value);
            forma.submit();
        }
        document.MM_returnValue = (errors == '');
    }



