String.prototype.pad = function( l, s, t ) {
	return s || ( s = " " ), ( l -= this.length ) > 0 ? ( s = new Array( Math.ceil( l / s.length )
			+ 1 ).join( s ) ).substr( 0, t = !t ? l : t == 1 ? 0 : Math.ceil( l / 2 ) )
			+ this + s.substr( 0, l - t ) : this;
};

var fnG = {
	obtieneLayer: function( id ) {
		if ( document.getElementById ) {
			return document.getElementById( id ).style;
		} else if ( document.all ) {
			return document.all[id].style;
		} else if ( document.layers ) {
			return document.layers[id];
		}
	},
	
	cargaCombo: function( valorCombo, comboLlenar, nombreArreglo ) {
		var numValores;
		var j, k = 1;
		
		while ( comboLlenar.length > 1 ) {
			comboLlenar.remove( 1 );
		}
		if ( valorCombo == 0 ) {
			comboLlenar.length = 1;
			comboLlenar.options[0].value = "0";
			comboLlenar.options[0].text = "Seleccione";
			comboLlenar.selectedIndex = 0;
			return false;
		}
		eval( 'varCases = cases' + nombreArreglo + '.valueOf();' );
		eval( 'switch( valorCombo ) { ' + varCases + ' default	: 	numValores = 0; comboLlenar.selectedIndex = 0; k = 0; }' );
		comboLlenar.selectedIndex = 0;
		return true;
	},

	extraeTexto: function( tupla ) {
		return tupla.substring( tupla.indexOf('!') + 1, tupla.length )
	},
	
	extraeValor: function( tupla ) {
		return tupla.substring( 0, tupla.indexOf('!') )
	},
	
	obtenerKeyCode: function( e ) {
		return window.event ? window.event.keyCode : ( e && typeof e.which != 'undefined' ) ? e.which : ( e && typeof e.keyCode != 'undefined' ) ? e.keyCode : null;
	},
	
	obtenerTarget: function( e ) {
		return ( window.event && window.event.srcElement ) ? window.event.srcElement : ( e && e.target ) ? e.target : 0;
	},

	obtElemPorPrefijo: function( idFormulario, preFijo, tipoElem ) {
		var numElementos = idFormulario.elements.length;
		var arrayDevolver = new Array();
		for ( var i = 0; i < numElementos; i++ ) {
			elemento = idFormulario.elements[i];
			if ( tipoElem != null ) {
				switch ( elemento.type ) {
					case tipoElem:
							if ( elemento.name.indexOf( preFijo ) != -1 && elemento.name.indexOf( preFijo ) == 0 ) {
								arrayDevolver.push( elemento );
							}
							break;
				}
			} else if ( elemento.name.indexOf( preFijo ) != -1 && elemento.name.indexOf( preFijo ) == 0 ) {
				arrayDevolver.push( elemento );
			}
		}
		return arrayDevolver;
	},
	
	obtTagHTMLPorPrefijo: function( nombreTag, preFijo ) {
		if ( !document.getElementsByTagName || nombreTag == null ) {
			return;
		}
		var arrayDevolver = new Array();
		var todosLosTags = document.getElementsByTagName( '' + nombreTag + '' );
		for ( var i = 0; i < todosLosTags.length; i++ ) {
			var tag = todosLosTags[i];
			if ( preFijo != null ) {
				if ( ( ' ' + tag.id + ' ' ).indexOf( preFijo ) != -1 && ( ' ' + tag.id + ' ' ).indexOf( preFijo ) == 1 ) {
					arrayDevolver.push( tag );
				}
			} else {
				arrayDevolver.push( tag );
			}
		}
		return arrayDevolver;
	},

	obtElem: function( id ) {
		if ( document.getElementById ) {
			return document.getElementById( id );
		} else if ( window[id] ) {
			return window[id];
		}
		return null;
	},
	
	addEvent: function( elm, evType, fn, useCapture ) {
		if ( elm.addEventListener ) { 
			elm.addEventListener( evType, fn, useCapture );
			return true;
		} else if ( elm.attachEvent ) { 
			var r = elm.attachEvent( 'on' + evType, fn ); 
			return r;
		} else {
			elm['on' + evType] = fn;
		}
	},
	
	caracteresValidos: function( e, ExpRegNoAceptados ) {
		var key = fnG.obtenerKeyCode( e );
		var caracterEntrada = String.fromCharCode( key );
		return !( caracterEntrada.match( ExpRegNoAceptados ) );
	},
	
	alerta: function( mensaje, objeto ) {
		alert( mensaje );
		objeto.focus();
		return false;
	},
	
	trim: function( s ) {
		while ( s.substring( 0, 1 ) == ' ' || s.substring( 0, 1 ) == '\t' ) {
			s = s.substring( 1, s.length );
		}
		while ( s.substring( s.length - 1, s.length ) == ' ' || s.substring( s.length - 1, s.length ) == '\t' ) {
			s = s.substring( 0, s.length - 1 );
		}
		return s;
	},
	
	borraEspacios: function( idFormulario ) {
		var elementos;
		elementos = idFormulario.elements.length;
		for ( var i = 0; i < elementos; i++ ) {
			elem = idFormulario.elements[i];
			switch ( elem.type ) {
				case "text": elem.value = fnG.trim( elem.value );
							break;
			}
		}
	},
	
	fechaMayor: function( dia1, mes1, anio1, dia2, mes2, anio2 ) {
		var fechaInicio = "";
		var fechaFin = "";
		fechaInicio = anio1 + mes1 + dia1;
		fechaFin = anio2 + mes2 + dia2;
		return ( fechaInicio > fechaFin )
	},

	llenadiaParteDeCero: function( comboDia, mes, ano ) {
		var maximo = 31;
		var maxdia = comboDia.options[comboDia.selectedIndex].value;
		for ( var i = comboDia.options.length; i > 0; i-- ) { 
			comboDia.options[i] = null;
		}
		if ( mes == '4' || mes == '6' || mes == '9' || mes == '11' ) {
			maximo = 30;
		}
		if ( mes == '2' ) {
			maximo = 28;
			var flagbiciesto = eval( ( ano % 4 == 0 ) && ( ( ano % 100 != 0 ) || ( ano % 400 == 0 ) ) );
			if ( flagbiciesto ) {
				maximo = 29;
			}
		}
		comboDia.options[0] = new Option( "Día", 0 );
		for ( var j = 1; j <= maximo; j++ ) {
			var valOption = ""
			var cero = "0";
			var newVal = 0;
			newVal = j;
			valOption = "" + newVal + "";
			if ( parseInt( valOption ) < 10 ) {
				valOption = cero.concat( valOption );
			}
			comboDia.options[j] = new Option( valOption, j );
		}
		if ( maxdia >= maximo ) {
			comboDia.options[maximo].selected = true
		} else {
			comboDia.options[maxdia].selected = true
		}
	},

	llenadia: function( comboDia, mes, ano ) {
		var maximo = 31;
		var maxdia = comboDia.options[comboDia.selectedIndex].value;
		for ( var i = comboDia.options.length; i > 0; i-- ) { 
			comboDia.options[i] = null;
		}
		if ( mes == '4' || mes == '6' || mes == '9' || mes == '11' ) {
			maximo = 30;
		}
		if ( mes == '2' ) {
			maximo = 28;
			var flagbiciesto = eval( ( ano % 4 == 0 ) && ( ( ano % 100 != 0 ) || ( ano % 400 == 0 ) ) );
			if ( flagbiciesto ) {
				maximo = 29;
			}
		}
		for ( var j = 0; j < maximo; j++ ) {
			var valOption = ""
			var cero = "0";
			var newVal = 0;
			newVal = j + 1;
			valOption = "" + newVal + "";
			if ( parseInt( valOption ) < 10 ) {
				valOption = cero.concat( valOption );
			}
			comboDia.options[j] = new Option( valOption, j + 1 );
		}
		if ( maxdia >= maximo ) {
			comboDia.options[maximo - 1].selected = true
		} else {
			comboDia.options[maxdia - 1].selected = true
		}
	},

	llenadiaSinAnio: function( comboDia, mes ) {
		var ano = 2000;
		var maximo = 31;
		var maxdia = comboDia.options[comboDia.selectedIndex].value;

		for ( var i = comboDia.options.length; i > 0; i-- ) { 
			comboDia.options[i] = null;
		}
		if ( mes == '4' || mes == '6' || mes == '9' || mes == '11' ) {
			maximo = 30;
		}
		if ( mes == '2' ) {
			maximo = 28;
			var flagbiciesto = eval( ( ano % 4 == 0 ) && ( ( ano % 100 != 0 ) || ( ano % 400 == 0 ) ) );
			if ( flagbiciesto ) {
				maximo = 29;
			}
		}
		for ( var j = 0; j < maximo; j++ ) {
			var valOption = ""
			var cero = "0";
			var newVal = 0;
			newVal = j + 1;
			valOption = "" + newVal + "";
			if ( parseInt( valOption ) < 10 ) {
				valOption = cero.concat( valOption );
			}
			comboDia.options[j] = new Option( valOption, j + 1 );
		}
		if ( maxdia >= maximo ) {
			comboDia.options[maximo - 1].selected = true
		} else {
			comboDia.options[maxdia - 1].selected = true
		}
	},

	muestraMensaje: function( div, flag ) {
		var DHTML = ( document.getElementById || document.all || document.layers );
		if ( !DHTML ) {
			return;
		}
		var x = fnG.obtieneLayer( div );
		x.visibility = ( flag ) ? 'visible' : 'hidden'
		if ( !document.getElementById ) {
			if ( document.layers ) {
				x.left = 280 / 2;
			}
		}
	},

	obtContenido: function( URL, fn ) {
		if ( !Sarissa ) {
			alert( "No está agregada la Librería Sarissa." );
			return;
		}
		var xmlhttp = new XMLHttpRequest();
		var fecha = new Date();
		var timestamp = fecha.getTime();
		var qs = URL + '&t=' + timestamp;
		xmlhttp.open( 'GET', URL + qs, true );
		xmlhttp.onreadystatechange = function() {
			if ( xmlhttp.readyState == 4 ) {
				fn ( unescape( xmlhttp.responseText ) );
			}
		};
		xmlhttp.send( null );
	},

	modulo11: function( dv, rut ) {
		var suma = 0;
		var mult = 2;
	
		if ( dv == "K" ) {
			dv = "10";
		}
		for ( i = rut.length - 1; i >= 0; i-- ) {
			c = rut.charAt(i);
			suma += parseInt( c, 10 ) * mult;
			mult++;
			if ( mult > 7 ) {
				mult = 2;
			}
		}
		var dvCalculado = 11 - suma % 11;
		if ( dvCalculado == 11 ) {
			dvCalculado = 0;
		}
		return( parseInt( dv ) == dvCalculado );
	},
	
	validaRut: function( valorRut, valorDV ) {
		if ( !valorRut || !valorDV ) {
			return false;
		}
		var ElRut = valorRut.toUpperCase();
		var ElDv = valorDV.toUpperCase();
		var rut00 = "000000000";
		if ( ( ElRut.length < 5 ) || ( ElRut.substring( 0, 1 ) == "0" ) || ( rut00.substring( 0, ElRut.length ) == ElRut ) 
								  || ( ElRut.length == 0 ) || ( ElDv.length == 0 ) ) {
			return false;
		}
		for ( i = 0; i < ElRut.length; i++ ) {
			c = ElRut.charAt( i );
			if ( c < "0" || c > "9" ) {
				return false;
			}
		}
		c = ElDv.charAt(0);
		if ( ( c < "0" || c > "9" ) && c != "K" ) {
			return false;
		}
		return fnG.modulo11( ElDv, ElRut );
	},
	
	esEmail: function( email ) {
		var filtro=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
		return filtro.test( email );
	},

	obtFechaMensaje: function( x ) {
		return x == 0 ? "Fecha válida"
		: x == 1 ? "Formato de fecha inválido"
		: x == 2 ? "Día no válido"
		: x == 3 ? "Mes no válido"
		: x == 4 ? "En Abril, Junio, Septiembre y Noviembre no hay día 31"
		: x == 5 ? "Febrero sólo tiene 28 días"
		: x == 6 ? "En años bisiestos, Febrero tiene 29 días": "nada =]";
	},

	esFecha: function( y, m, d ) { 
		if ( typeof y == "string" && m instanceof RegExp && d ) {
			if ( !m.test( y ) ) {
				return 1;
			}
			y = RegExp[ "$" + d.y ], m = RegExp[ "$" + d.m ], d = RegExp[ "$" + d.d ];
		}
		d = Math.abs( d ) || 0, m = Math.abs( m ) || 0, y = Math.abs( y ) || 0;
		return arguments.length != 3 ? 1 : d < 1 || d > 31 ? 2 : m < 1 || m > 12 ? 3 : /4|6|9|11/.test( m ) && d == 31 ? 4
		: m == 2 && ( d > ( ( y = !( y % 4 ) && ( y % 1e2 ) || !( y % 4e2 ) ) ? 29 : 28 ) ) ? 5 + !!y : 0;
	},

	Get_Cookie: function( name ) {
		var start = document.cookie.indexOf( name + "=" );
		var len = start + name.length + 1;
		if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
			return null;
		}
		if ( start == -1 ) {
			return null;
		}
		var end = document.cookie.indexOf( ";", len );
		if ( end == -1 ) {
			end = document.cookie.length;
		}
		return unescape( document.cookie.substring( len, end ) );
	},
	
	Set_Cookie: function( name, value, expires, path, domain, secure ) {
		var today = new Date();
		today.setTime( today.getTime() );
		if ( expires ) {
			expires = expires * 1000 * 60 * 60 * 24;
		}
		var expires_date = new Date( today.getTime() + (expires) );
	
		document.cookie = name + "=" + escape( value ) +
			( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
			( ( path ) ? ";path=" + path : "" ) + 
			( ( domain ) ? ";domain=" + domain : "" ) +
			( ( secure ) ? ";secure" : "" );
	},
	
	Delete_Cookie: function( name, path, domain ) {
		if ( fnG.Get_Cookie( name ) ) document.cookie = name + "=" +
				( ( path ) ? ";path=" + path : "") +
				( ( domain ) ? ";domain=" + domain : "" ) +
				";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	},
	
	mostrar: function( queMostrar, valor ) {
		fnG.obtElem( queMostrar ).style.display = valor;
	},
	
	previsualizarImagen: function( idFormulario, campoImagen, campoDesplegar, divContenedor ) {
		var filename;
		var objImagen;
		if ( document.images ) {
			filename = idFormulario.campoImagen.value;
			objImagen = new Image();
			objImagen.src = filename;
			idFormulario.campoDesplegar.src = objImagen.src;
			fnG.mostrar( divContenedor, "inline" );
		} else {
			fnG.alerta( "Su browser no soporta pre-visualización de imágenes.", idFormulario.campoImagen );
		}
	},

	esNumero: function( numero ) {
		var expReg = /^[0-9]+$/i;
		return expReg.test( numero );
	},
	
	noInputSoloNumeros: function( e ) {
		var charCode;
		if ( navigator.appName == "Netscape" ) {
			charCode = e.which;
		} else {
			charCode = e.keyCode;
		}
		sw = 0;
		status = charCode;
		if ( ( charCode >= 48 ) && ( charCode <= 57 ) ) {
			sw = 1;
		}
		if ( ( charCode == 0 ) || ( charCode == 8 ) ) {
			sw = 1;
		}
		if ( navigator.appName == "Netscape" ) {
			if ( sw == 0 ) {
				return false;
			}
		} else {
			if ( sw == 0 ) {
				event.returnValue = false;
			}
		}
	},
	
	noInputSoloDV: function( e ) {
		var charCode;
		if ( navigator.appName == "Netscape" ) {
			charCode = e.which;
		} else {
			charCode = e.keyCode;
		}
		sw = 0;
		status = charCode;
		if ( ( charCode >= 48 ) && ( charCode <= 57 ) ) {
			sw = 1;
		}
		if ( ( charCode == 75 ) || ( charCode == 107 ) ) {
			sw = 1;
		}
		if ( ( charCode == 0 ) || ( charCode == 8 ) ) {
			sw = 1;		
		}
		if ( navigator.appName == "Netscape" ) {
			if ( sw == 0 ) {
				return false;
			}
		} else {
			if ( sw == 0 ) {
				event.returnValue = false;
			}
		}
	},
	
	validaRutPuntos: function ( valor ) {
	    var regExp = /^([0-9]{1,3}((\.[0-9]{1,3})|([0-9]{1,3}))+|[0-9]{7,8})(\-([0-9]|k|K)|([0-9]|k|K))$/i;
	    return regExp.test( valor );
	},
	
	ponePuntosRut: function ( rut ) {
	
	    if ( fnG.validaRutPuntos(rut) ) {
	    
	        rut = rut.split(".").join("");
    	    rut = rut.split("-").join("");
    	    rut = rut.substr(0 , rut.length - 1) + "-" + rut.substr( rut.length - 1, 1 );
    	    rut = rut.split('-');
    	    
	        var rutConPuntos = '';
	        var i = 1;
    	    
            for (n = (rut[0].length - 1); n>=0 ; n--) {
            
                rutConPuntos = String(rut[0].substr(n,1)) + String(rutConPuntos);
                if (i==3) {
                    i = 1;
                    rutConPuntos = "." + String(rutConPuntos);
                } else {
                    i++;
                }
                
            }
            return rutConPuntos + "-" + rut[1];
            
        } else {
            return rut;
        }
        
	}
}
