
String.prototype.trim = function() {

	var str = this.replace(/^\s*/g,"");
		str = str.replace(/\s*$/g,"");
	return str;
}

String.prototype.soLetras = function() {
	return this.replace(/[^A-Za-z ]/g,'');
}

String.prototype.unLast = function() {
	return this.substring(0, this.length - 1);
}

String.prototype.quebraLinha = function() {

	var valor = this;

	while( valor.indexOf("\n") > 0 ) {
		valor = valor.replace("\n","<BR>");
	}

	return valor;
}

Array.prototype.retiraUltimaPosicao = function() {
	return this.splice(this.length-1,1);
}

var Util = {

	getEl : function(id) {
		return document.getElementById(id);
	},

	getXY : function(element) {

		var curleft = 0;
		var curtop = 0;
		
		obj = Util.getObj(element);
		
		if (obj.offsetParent)
		{
			while (obj.offsetParent)
			{
				curleft += obj.offsetLeft
				obj = obj.offsetParent;
			}
		}
		else if (obj.x)
			curleft += obj.x;
			
		obj = element;
		if (obj.offsetParent)
		{
			while (obj.offsetParent)
			{
				curtop += obj.offsetTop
				obj = obj.offsetParent;
			}
		}
		else if (obj.y)
			curtop += obj.y;
	
	
		a = new Array();
		
		a[0] = curleft;	
		a[1] = curtop;
		return a;	
	},

	getWH: function(el) {

		var el = Util.getObj(el);

		return [ el.offsetWidth.toString() , el.offsetHeight.toString() ];
	},

	data : {
		db2Visual : function(stringData) {

			if( Validacao.espaco(stringData) ) {
				return stringData;
			}

			var arrData = stringData.split("-");
			
			return arrData[2]+"/"+arrData[1]+"/"+arrData[0];
		}
	},

	getObj : function(el) {

		if(Util.isString(el)) {
			return Util.getEl(el);
		}
		return el;
	},

	removeAllChildNodes : function(el) {

		var pai = Util.getObj(el);

		if( pai.firstChild &&  pai.firstChild.nodeName.toLowerCase() == "tbody" ) {

			while( pai.rows[0] ) {
				pai.deleteRow(0);
			}
		} else {

			while( pai.firstChild ) {
				pai.removeChild(pai.firstChild);
			}
		}
	},

	manipulaEl : function(el,m) {
		
		var	el = Util.getObj(el);
		
		if( el ) {

			switch( m ) {
				case "hide" : 
					Util.display.hide( el);
				break;
				case "show" : 
					Util.display.show( el);
				break;
				case "clear" : 
					el.innerHTML = "";
				break;
				case "remove" : 

					var parent = el.parentNode;

					if( parent ) {
						parent.removeChild(el);
					}
				break;
			}
		}
	},

	display : {
		
		isVisible : function( el) {

			var display = Util.getObj(el).style.display;
			
			return display == "block" || display == "";
		},

		show : function( el) {
			Util.getObj(el).style.display = "";
		},

		hide : function( el) {
			Util.getObj(el).style.display = "none";
		}
	},

	setEvent2CampoArray : function( f, sc, mEv, fnc) {

		var el;

		for( var i=0; i < f.elements.length; i++ ) {
			el = f.elements[i];
			if( el.name == sc ) {
				eval( "el."+mEv+" = fnc");
			}
		}
	},

	campoReadonly : function(campo) {

		var obj = Util.getObj(campo);

		obj.readOnly = true;
/*
		obj.onkeypress = function() {
			return false;
		}

		obj.style.backgroundColor 		= "#f2f2f2";
		obj.style["background-color"] 	= "#f2f2f2";
*/
	},

	campoAbil : function(campo) {

		var obj = Util.getObj(campo);

		obj.readOnly = false;	

/*
		obj.onkeypress = function() {
			return true;
		}

		obj.style.backgroundColor 		= "#fff";
		obj.style["background-color"] 	= "#fff";
*/
	},

	textoSelect : function( elSelect) {
		if( elSelect.selectedIndex>-1) {
			return elSelect.options[elSelect.selectedIndex].text;
		} else {
			return false;
		}	
	},

	removeFromSelect : function(elSelect,valor) {

		var op;

		for(var i=0;i<elSelect.length;i++) {

			if( elSelect.options[i].value.toLowerCase() ==  valor.toLowerCase() ) {
				elSelect.removeChild( elSelect.options[i] );
				break;
			}
		}
	},

	formataValor : function ( valor) {
		return Util.moeda.formataNumero( valor);
	},

	moeda : {
		formataNumero : function( valor) {

			var valor = valor.toString();
	
			var len = valor.length;
	
			var novoValor = '';
	
			if( valor != '' ){	
	
				if ( len <= 2 ) {
					if ( len == 1) {
						novoValor = "0,0" + valor ;
					} else {
						novoValor = "0," + parseInt(valor);
					}
				} else {
					
					novoValor = "," + valor.substring(len-2,len+2);
	
					var dot;
					
					for( var i = 3 ; i <= len; i++ ) {
						
						dot = ( ( i > 3 && i%3 == 0 ) ? '.' : '' );
	
						novoValor = valor.substring(len-i,len+1-i) + dot + novoValor;
					}
				}
			}
	
			return novoValor;
		},
		
		numero : function( valor) {
			var valor = valor.replace( /[\.,]/g,"");
			return Math.abs( valor);
		}
	},

	checaCampoRadio : function(campoRadio,value) {

		if(!campoRadio) {
			return false;
		}

		for( var x=0; x < campoRadio.length; x++ ) {

			if( campoRadio[x].value == value ) {
				campoRadio[x].checked = true;
				break;
			}
		}
	},

	nextSibling : function( n) {

		var x = n.nextSibling;

		if( x) {

			while( x.nodeType!=1 ) {
				x = x.nextSibling;
			}
			return x;
		}
		
		return false;
	},

	insertAfter : function( novaLinha, linha) {

		var proximaLinha = Util.nextSibling( linha);

		if( proximaLinha ) {
			proximaLinha.parentNode.insertBefore( novaLinha , proximaLinha);
		} else {
			linha.parentNode.appendChild( novaLinha, linha);
		}
	},

	html : {

		checaCampoCheckbox : function( formulario, nomeCampo, valor) {

			for( var init = 0 ; init < formulario.elements.length ; init++) {
				var el = formulario.elements[init];
				if( el.name	== nomeCampo && el.value == valor ) {
					el.checked = true;
					break;
				}
			}
		},

		novoInput : function( att) {

			if( Util.isUdf(att)) var att = {};

			var id		= att.id ? att.id : "";
			var name	= att.name ? att.name : "";
			var value	= att.value ? att.value : "";
			var selected= att.selected;
			var type	= att.type ? att.type : "text";
			var add		= att.add ? att.add : "";

			var input;

			switch( type) {
				case 'radio' : break;
				case 'checkbox' : 
				
					if( selected) {
						selected = "checked";
					}
				
					input = "<input id='"+id+"' type='"+type+"' name='"+name+"' value='"+value+"' "+add+" "+selected+" >";
				break;
				default : 
	
					input = document.createElement('INPUT');
	
					input.id = id;
					input.name = name;
					input.type = type;
					input.value = value;
				break;
			}

			return input;
		},

		appendOption : function(campoSelect,newOption) {
		
			try{
				campoSelect.add(newOption,null);
			} catch (e) {
				campoSelect.add(newOption);
			}
		},

		criaSelect : function( arrOption, objOption ) {

			if( !Util.isObj(arrOption) || Util.isUdf(objOption) ) {
				arrOption = {
					value		: "",
					text		: "",
					selected	: false
				};
			}

			var campoSelect = document.createElement("SELECT");

			if( !objOption ) {

				for( var i=0 ; i < arrOption.length ; i++ ) {

					var newOption			= document.createElement("OPTION");
						newOption.value		= arrOption[i].value	? arrOption[i].value : "";
						newOption.text		= arrOption[i].text		? arrOption[i].text : "";
						newOption.selected	= arrOption[i].selected ? true : false ;

					Util.html.appendOption( campoSelect, newOption);
				}
			} else {

				for(var c = 0; c < arrOption.length; c++) {
					Util.html.appendOption(campoSelect,arrOption[i]);
				}
			}

			return campoSelect;
		}
	},

	valorRadio : function( campoRadio ) {

		if(!campoRadio) {
			return false;
		}

		for( var x=0; x < campoRadio.length; x++ ) {

			if( campoRadio[x].checked ) {
				return campoRadio[x].value;
			}
		}
	},

	isNumber : function(n) {
		return /^\d{1,}$/.test(n);
	},
	
	
	isString : function(el) {
		return (typeof el == "string");
	},
	
	isObj : function(el) {
		return (typeof el =="object");
	},
	
	isUdf : function(el) {
		return (typeof el =="undefined");
	},
	
	getRandomId : function() {

		var randomId = parseInt(540 * Math.random());
		
		return randomId.toString();
	},
	
	isNull : function(el) {
		return (el == null);
	},
	
	isEmpty : function(el) {
		var re = /^\s+$/;
		if(re.test(el) || el=="")
			return true;
		else
			return false;
	},
	
	isArray : function() {
		return (typeof el == "array");
	}
}

Util.CSS = {

	// propriedades que mudam de nome do IE para o Mozilla...

	rulesName	: function() {
		return Util.Browser.isIe() ? 'rules' : 'cssRules';
	},

	domNode	: function() { 
		return Util.Browser.isIe() ? 'owningElement' : 'ownerNode';
	},

	gi : function() {

		var stl = document.styleSheets;

		var arrInst = [];

		var rulesName = Util.CSS.rulesName();

		for(var i = 0; i < stl.length; i++) { // para cada elemento de estilo na p&aacute;gina

			for(var g = 0; g < stl[i][rulesName].length; g++) { // para cada regra desse elemento

				// o seletor
				// o cssText (os replaces apenas colocam quebras de linha e um 
				// ponto-e-v&iacute;rgula no final, caso n&atilde;o exista)

				arrInst.push(stl[i][rulesName][g]);

				// +' {\n'+ 
				//stl[i][rulesName][g].style.cssText.replace(/;?\s*$/, ';').replace(/;\s*/g, ';\n')+'}');
			}
		}

		return arrInst;
	},

	addRule : function(newStyle) {

		if ( document.styleSheets[0].addRule ) { // Browser is IE?
			document.styleSheets[0].addRule(newStyle.getNome(), null,0);// Yes, add IE style
		} else {// Browser is IE?
			document.styleSheets[0].insertRule(newStyle.getNome()+' { }', 0); // Yes, add Moz style.
		}// End browser check
	},

	addAttributeStyle : function(newStyle) {

		var arrInstances = Util.CSS.gi();

		var instance=null,arrAttributes=null;

		for(var i = 0; i < arrInstances.length; i++) { // para cada elemento de estilo na p&aacute;gina

			if( arrInstances[i].selectorText.replace().toLowerCase() != newStyle.getNome().toLowerCase() ) {
				continue;
			} else {
				instance = arrInstances[i];
			}
		}

		if( instance == null ) {
			Util.CSS.addRule(newStyle);
			instance = document.styleSheets[0][Util.CSS.rulesName()][0];
		}

		arrAttributes = newStyle.getAttributes();

		for( var x = 0; x < arrAttributes.length ; x++ ) {
			eval("instance.style." + arrAttributes[x].getNome() + " = arrAttributes[x].getValor()");
		}
	}
}

Util.Style = function(nome) {

	this.nome = nome;

	this.getNome = function() {
		return this.nome;
	}

	this.att = [];

	this.Attribute = function(nome,valor) {

		this.nome = nome;
		this.valor = valor;

		this.getNome = function() {
			return this.nome;
		}
	
		this.getValor = function() {
			return this.valor;
		}
	}

	this.setAttribute = function(nome,valor) {
		this.att.push( new this.Attribute(nome,valor) );
	}

	this.getAttributes = function() {
		return this.att;
	}
}

Util.Browser = {
	
	agt : navigator.userAgent.toLowerCase(),
	
	isOpera : function() {
		return (Util.Browser.agt.indexOf('opera') > -1)
	},

	isSafari : function() {
		return (Util.Browser.agt.indexOf('safari') > -1)
	},

	isIe : function() {
		return (!Util.Browser.isOpera() && 
				Util.Browser.agt.indexOf('msie') > -1)
	},
    
    isIe6 : function() {

		return 	Util.Browser.isIe() && 
				parseInt(navigator.appVersion) == 4 && 
				Util.Browser.agt.indexOf("msie 6.") != -1 ;

	},

	isGecko : function() {
		return (!Util.Browser.isOpera() && 
				!Util.Browser.isSafari() && 
				Util.Browser.agt.indexOf("gecko") != -1);
	},

	xy : function() {

		var scrOfX = 0, scrOfY = 0;
		if( typeof( window.pageYOffset ) == 'number' ) {
				  //Netscape compliant
			scrOfY = window.pageYOffset;
			scrOfX = window.pageXOffset;
		} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
				  //DOM compliant
			scrOfY = document.body.scrollTop;
			scrOfX = document.body.scrollLeft;
		} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
				  //IE6 standards compliant mode
			scrOfY = document.documentElement.scrollTop;
			scrOfX = document.documentElement.scrollLeft;
		}
		return [ scrOfX, scrOfY ];
	},
	
	wh : function() {

		var w = 0, h = 0;

		if( typeof( window.innerWidth ) == 'number' ) {
		  //Non-IE
			w = window.innerWidth;
			h = window.innerHeight;
		} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		  //IE 6+ in 'standards compliant mode'
			w = document.documentElement.clientWidth;
			h = document.documentElement.clientHeight;
		} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		  //IE 4 compatible
			w = document.body.clientWidth;
			h = document.body.clientHeight;
		}
		return [ w, h];
	}
}

Util.Window = function() {

	this.url	= "about:blank";

	this.title	= "";

	this.width	= null;
	this.height	= null;
	this.top	= null;
	this.left	= null;
	this.status = null;

	this.setUrl = function( url) {
		this.url = url;
	}

	this.setTitle = function( title) {
		this.title = title;
	}

	this.setWidth = function( width) {
		this.width = width;
	}

	this.setHeight = function( height) {
		this.height = height;
	}

	this.setTop = function( top) {
		this.top = top;
	}

	this.setLeft = function( left) {
		this.left = left;
	}

	this.setStatus = function( status) {
		this.status = status;
	}

	this.getUrl = function() {
		return this.url;
	}

	this.getTitle = function() {
		return this.title;
	}

	this.getWidth = function() {
		return this.width;
	}

	this.getHeight = function() {
		return this.height;
	}

	this.getTop = function() {
		return this.top;
	}

	this.getLeft = function() {
		return this.left;
	}

	this.getStatus = function() {
		return this.status;
	}
	
	this.open = function() {

		var arrAt = [];
		
		if( this.width != null ) {
			arrAt.push("width=" + this.width.toString());
		}
		
		if( this.height != null ) {
			arrAt.push("height=" + this.height.toString());
		}
		
		if( this.top != null ) {
			arrAt.push("top=" + this.top.toString());
		}
		
		if( this.left != null ) {
			arrAt.push("left=" + this.left.toString());
		}

		if( this.status ) {
			arrAt.push("status=yes");
		} else {
			arrAt.push("status=no");
		}

		window.open( this.url, this.title, arrAt.join(","));
	}

	this.close = function() {
		window.close();
	}
}

Util.Cookie = {

	create : function (name,value,time) {

		var segundos = 0;
		
		if( time.dias) {
			segundos = time.dias*24*60*60;
		} else if( time.segundos) {
			segundos = time.segundos;
		} else if( time.minutos) {
			segundos = time.minutos*60;
		} else if( time.horas) {
			segundos = time.horas*60*60;
		}

		if ( segundos) {
			var date = new Date();
			date.setTime(date.getTime()+(segundos*1000));
			var expires = "; expires="+date.toGMTString();
		}

		else var expires = "";

		document.cookie =	name +
							"=" +
							Util.Cookie.read(name) +
							value + 
							expires +
							"; path=/";
	},	

	read : function (name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');

		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return "";
	},

	erase : function (name) {
		Util.Cookie.create(name,"",{dias : -1 });
	}
}

Util.LenChar = {

	idEl2Count : [],
		
	contador : 0,

	maximo : 2500,
	
	id2Write : "",
	
	controla : function(arr,maxSize,id2String) {
		
		Util.LenChar.idEl2Count	= arr;
		Util.LenChar.maximo		= Util.isUdf(maxSize) ? 2500 : maxSize;
		Util.LenChar.id2String	= Util.isUdf(id2String) ? "" : id2String;
		
		
		for(var x=0;x < Util.LenChar.idEl2Count.length;x++) {
			
			Util.getObj(Util.LenChar.idEl2Count[x]).onkeyup = function() {
				return Util.LenChar.updateStringLength(this);
			}
		}
	},

	updateStringLength : function(field) {

		var count = 0;
		
		for(var c=0;c<Util.LenChar.idEl2Count.length;c++) {

			var element = Util.getObj(Util.LenChar.idEl2Count[c]);
			count+= Number(element.value.length);
		}
	
		var numCharRes	= Util.LenChar.maximo - count; // Número de caracteres restantes
	
		if(numCharRes<0) {
			
			var qtdwoutfield = count - field.value.length; // Quantidade de caracteres sem este campo
			var qtdrest		 = Util.LenChar.maximo - qtdwoutfield;     // Quantidade de caracteres restante para este campo
			field.value		 = field.value.substring(0,qtdrest);

			alert('O conteúdo ultrapassou o limite de ' + Util.LenChar.maximo + ' caracteres!');

			Util.getObj(Util.LenChar.id2String).innerHTML = 'Caracteres restantes: 0';

			return false;

		} else {

			Util.getObj(Util.LenChar.id2String).innerHTML = 'Caracteres restantes: ' + numCharRes;
			return true;
		}
	}
}

JSIframe = {

	create : function(id,src) {
		
		var iframe = document.createElement("IFRAME");
			iframe.setAttribute("id",id);
			iframe.setAttribute("name",id);

		if(!Util.isUdf(src) && Util.isNull(src)) {
			iframe.src = src;
		}
		
		return iframe;
	}
}

var JSEvent = {

	addEventSimple : function(obj,evt,fn) {
		
		var obj = Util.getObj(obj);

		if (obj.addEventListener)
			obj.addEventListener(evt,fn,false);
		else if (obj.attachEvent)
			obj.attachEvent('on'+evt,fn);
	},

	removeEventSimple : function(obj,evt,fn) {

		var obj = Util.getObj(obj);

		if (obj.removeEventListener)
			obj.removeEventListener(evt,fn,false);
		else if (obj.detachEvent)
			obj.detachEvent('on'+evt,fn);
	}
}