// JavaScript Document

//*************************************************************************************************************************//
// método que formata a entrada para o tipo data (ex: 01/01/2006)
	function toUpper(e){
		if (e != null)
			var key = (window.event) ? window.event.keyCode : e.which;
		else
			var key = window.event.keyCode;

		if (key >= 97 && key <= 122){
			if (e != null){
				if (window.event){
					window.event.keyCode = key - 32;
				}
				else e.which = key - 32;
			} else {
				if (window.event) window.event.keyCode = key - 32;
			}
		} else return;
	}

//*************************************************************************************************************************//
// método que formata a entrada para o tipo data (ex: 01/01/2006)
	function dateFormat(origem,e){
		if (e != null)
			var key = (window.event) ? window.event.keyCode : e.which;
		else
			var key = window.event.keyCode;

		// se não for o navegador Opera
		if(navigator.userAgent.toLowerCase().indexOf('opera') == -1){
			//se for TAB ou DEL ou BACKSPACE ou ENTER
			if (key != 9 && key != 46 && key != 8 && key != 13){
				if (origem.value.length == 2) origem.value += '/';
				if (origem.value.length == 5) origem.value += '/';
			
				onlyChars('0123456789',e);
			}
		}
	}

//*************************************************************************************************************************//
// Método que auto-alinha as palavras em Upper/Lower Case
	function toUpperLower(str){
		var resultado = str.charAt(0).toUpperCase();							// jah transforma a primeira letra para UpperCase
		for(var i = 1; i < str.length; i++){									// loop do tamanho da string		
			if(str.charCodeAt(i-1) == 32){										// checa se a posição eh igual um espaço em branco
				resultado += str.charAt(i-1) + str.charAt(i).toUpperCase();		// transforma a primeira letra logo depois do espaço em UpperCase
			} else {
				while(str.charCodeAt(i) != 32 && i < str.length){				// loop rodando enquanto a letra for diferente de espaço e final da string
					resultado += str.charAt(i).toLowerCase();					// colca todas letras dessa intervalo em LowerCase
					i++;
				}
			}
		}
		return resultado;
	}

//***************************************************************************************************************
//método q formata os numeros de boleto para o padrao de boleto
	function formatBoleto(str){
		var newStr = "";
		for(var i = 0; i < str.length; i++){
			newStr += str.charAt(i);
			if (i == 4) newStr += ".";
			if (i == 9) newStr += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
			if (i == 14) newStr += ".";
			if (i == 20) newStr += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
			if (i == 25) newStr += ".";
			if (i == 31) newStr += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
			if (i == 32) newStr += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		}

		return newStr;
	}

//***************************************************************************************************************
// método que formata um número com casas numéricas definidas na entrada
// Entrada: 234 --> Saída: 234.00
// Entrada: 234.3333333334 --> Saída: 234.33
	function formatNumber(str,nro){
		var strRetorno = str.toString();
		if (strRetorno.indexOf(".") == -1) strRetorno += ".00";

		if (strRetorno.split(".").length == 2){
			if(strRetorno.split(".")[1].length > 2){
				strRetorno = strRetorno.split(".")[0] +"."+ strRetorno.split(".")[1].substring(0,nro);
			}
		}

		return strRetorno;
	}

//*************************************************************************************************************************//

//*************************************************************************************************************************//
// formata o input para moeda
	function formataValor(oCampo,tMax,ePress) {
		var tecla = ePress.keyCode;
		var vr = oCampo.value;

		vr = vr.replace( "/", "" );
		vr = vr.replace( "/", "" );
		vr = vr.replace( ",", "" );
		vr = vr.replace( ".", "" );
		vr = vr.replace( ".", "" );
		vr = vr.replace( ".", "" );
		vr = vr.replace( ".", "" );
		tam = vr.length;

		if (tam < tMax && tecla != 8) tam = vr.length + 1;
		if (tecla == 8) tam = tam - 1;		
		if (tecla == 8 || (tecla >= 48 && tecla <= 57) || (tecla >= 96 && tecla <= 105) ){
			if (tam <= 2) oCampo.value = vr;
			tam = tam - 1;
			if ((tam > 2) && (tam <= 5)) oCampo.value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam );
			if ((tam >= 6) && (tam <= 8)) oCampo.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam );
			if ((tam >= 9) && (tam <= 11)) oCampo.value = vr.substr( 0, tam - 8) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam );
			if ((tam >= 12) && (tam <= 14))	oCampo.value = vr.substr( 0, tam - 11) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam );
			if ((tam >= 15) && (tam <= 17))	oCampo.value = vr.substr( 0, tam - 14) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam );
		}
	}

//*************************************************************************************************************************//
// método que verifica se o navegador é Opera para poder formatar os campos CEP
	function doFormat(origem,e){
		if (e != null)
			var key = (window.event) ? window.event.keyCode : e.which;
		else
			var key = window.event.keyCode;

		// se não for o navegador Opera
		if(navigator.userAgent.toLowerCase().indexOf('opera') == -1){
			//se for TAB ou DEL ou BACKSPACE ou ENTER
			if (key != 9 && key != 46 && key != 8 && key != 13){
				if(origem.value.length == 5)
					origem.value += '-';
			
				onlyChars('0123456789');
			}
		}
	}

//*************************************************************************************************************************//
// método que faz o redirect das páginas
	function frameRedirect(local,frame,url){
		if(navigator.appName == "Netscape"){
			local.getElementById(frame).src = url;
		} else {
			local.frames[frame].location.href = url;
		}
	}

//*************************************************************************************************************************//
// método que faz o redirect das páginas
	function redirect(local,url,change){
		change = (change != null) ? change : false;

		if(navigator.appName == "Netscape"){
			local.location.href = url;
		} else {
			if (change)	local.location.replace(url);
			else local.location = url;
		}
	}

//**********************************************************************************************************//
	// - Método que seta a cor do background e fonte
	function mouseOut(identificador,tipo) {
		if (tipo != "") {
			with (identificador.style) {
				backgroundColor = tipo;
//				color = '#000000';
			 }
		} else {
			with (identificador.style) {
				backgroundColor = '#ffffff';
//				color = '#000000';
			}
		}
	}
	
//**********************************************************************************************************//
	// - Método que seta a cor do background, fonte e mouse
	function mouseOver(identificador,tipo,mouse) {
		if (tipo != "") {
			with (identificador.style) {
				cursor = mouse;
//				color = '#000000';
				backgroundColor = tipo;
			}
		} else {
			 with (identificador.style) {
				cursor = mouse;
//				color = '#ffffff';
//				backgroundColor = '#3169C6';
			}
		}
	}

//*************************************************************************************************************************//
// método que restringe apenas um conjunto de caracteres ao digitar no campo data. Parâmetro são os números que serão permitidos
	function onlyChars(cadeia,e){
		if (e != null)
			var key = (window.event) ? window.event.keyCode : e.which;
		else
			var key = window.event.keyCode;

		//se for TAB ou DEL ou BACKSPACE ou ENTER
		if (key == 9 || key == 46 || key == 8 || key == 13) return;

		var chars = cadeia;
		var ev = String.fromCharCode(key);

		if(chars.indexOf(ev) == -1){
			if (e != null){				
				if (window.event) {
					window.event.keyCode = 0;
				} //else
					//e.which = 0;
			} else
				if (window.event)
					window.event.keyCode = 0;
		}
	}

//*****************************************************************************************************************************//
	function getWidth(){
		var wWidth = 0;
		if (navigator.userAgent.indexOf("MSIE") > 0) {
			wWidth = document.body.clientWidth;
			return wWidth;
		} else {
			wWidth = window.outerWidth;
			return wWidth;
		}
	}

//*****************************************************************************************************************************//
	// - Método que abre um popup do tipo window.open,
	function newWindow(mypage,myname,w,h,scroll,rez,maxi,menu,tool,loc){
		var winl = (screen.width-w)/2;
		var wint = (screen.height-h)/2;
		var settings  = (maxi) ? 'top=0,' : 'top='+wint+',';
			settings += (maxi) ? 'left=0,' : 'left='+winl+',';
			settings += (menu != null) ? "menubar="+menu+"," : "";
			settings += (tool != null) ? "toolbar="+tool+"," : "";
			settings += (loc != null) ? "location="+loc+"," : "";
			settings +='scrollbars='+scroll+',';
			settings +='resizable='+rez+',';			
			settings += (maxi) ? 'width='+getScreenWidth()+',' : 'width='+w+',';
			settings += (maxi) ? 'height='+getScreenHeight()+',' : 'height='+h+',';
			settings +='innerwidth='+w+',';
			settings +='innerheight='+h;

		if (parseInt(navigator.appVersion) > 3){
			win = window.open(mypage,myname,settings);
			win.window.focus();
		} else
			alert("Seu navegador é muito antigo ou incompatível com esta função.");
	}

//*****************************************************************************************************************************//
	function getScreenWidth(){
		if (navigator.userAgent.indexOf("MSIE") > 0)		
			return screen.AvailWidth;
		else
			return screen.width;
	}

//*****************************************************************************************************************************//
	function getScreenHeight(){
		if (navigator.userAgent.indexOf("MSIE") > 0)		
			return screen.AvailHeight;
		else
			return screen.height;
	}

//***************************************************************************************************************
// método que adiciona numeros ZERO antes de dias/meses que são menores que 10.
// Entrada: 5/6/2005 --> Saída: 05/06/2005
	function addZeroDate(oDate){
		/*var newDate = "";
		var date = oDate.split("/");
		if (date.length != 3) return "";
		
		for (var i = 0; i < date.length; i++){
			newDate += (parseInt(date[i]) < 10) ? "0" + date[i] : date[i];
			if (i < date.length - 1) newDate += "/";
		}*/
		var newDate = "";
		var date = oDate.split("/");
		if (date.length != 3) return "";
		
		for (var i = 0; i < date.length; i++){
			newDate += (parseInt(date[i]) < 10) ? "" + date[i] : date[i];
			if (i < date.length - 1) newDate += "/";
		}
		
		return newDate;
	}

//***************************************************************************************************************
// retorna a data atual no formato: dd/mm/aaaa
	function setCurrentDate(objeto){
		var hj = new Date();
		var novaData = (hj.getDate() < 10) ? ("0" + hj.getDate() + "/") : (hj.getDate() - 1 + "/");
		novaData += (hj.getMonth() + 1 < 10) ? ("0" + (hj.getMonth() + 1) + "/") : ((hj.getMonth() + 1) + "/");
		novaData += (navigator.appVersion.indexOf("MSIE") != -1) ? hj.getYear() : hj.getYear() + 1900;
		objeto.value = novaData;
	}

//***************************************************************************************************************
	function currentDay(){
		var newDate = new Date();
		return newDate.getDate();
	}

//***************************************************************************************************************
	function currentMonth(){
		var newDate = new Date();
		return newDate.getMonth();
	}

//***************************************************************************************************************
	function currentYear(){
		var newDate = new Date();
		return (navigator.appVersion.indexOf("MSIE") != -1) ? newDate.getYear() : newDate.getYear() + 1900;
	}

//*************************************************************************************************************************//
// limita a qtde de caracteres exibidos
	function limitString(local,string,limit){
		var novaString = "";
		
		if (string.length > limit)
			for (var i = 0; i < limit; i++){
				novaString += string.charAt(i);
			}
		else
			return string;
		return novaString + "...";
	}

//*************************************************************************************************************************//
// método que trata a entrada dos dados entre fillHdn e clearHdn
	function fill(oHdn,obj,div){
		if (div == null) div = "_";

		if (obj.checked) fillHdn(oHdn,obj.value,div);
		else clearHdn(oHdn,obj.value,div);
	}

//*************************************************************************************************************************//
// método que preenche um input com valores separados por uma divisão qualquer de entrada para qualquer valor
	function putHdn(hdn,param,div){
		if (div == null) div = "_";

		// se o input hidden estiver vazio...
		if (hdn.value == "")
			hdn.value = param;
		else
			hdn.value += div + param;
	}

//*************************************************************************************************************************//
// método que preenche um input com valores separados por uma divisão qualquer de entrada
	function fillHdn(hdn,param,div){
		if (div == null) div = "_";

		// se o input hidden estiver vazio...
		if (hdn.value == ""){
			hdn.value = param;
		} else {
			//se o valor jah existir...
			if (hdn.value.indexOf(div + param + div) >= 0) return;
			//se o valor estiver na ultima posicao...
			if (hdn.value.substring(hdn.value.length-2,hdn.value.length).indexOf(div + param) >= 0) return;
			//se o valor estiver na primeira posicao...
			if (hdn.value.substring(0,2).indexOf(param + div) == 0) return;

			hdn.value += div + param;
		}
	}

//*************************************************************************************************************************//
// método que remove de input o valor passado por parametro (extenção de fillHdn(...))
	function clearHdn(hdn,param,div){
		if (div == null) div = "_";

		//se estiver na primeira posição...
		if (hdn.value.indexOf(param) == 0)
			//se for somente uma foto selecionada...
			if ((hdn.value.indexOf(div)) == -1)
				hdn.value = hdn.value.replace(param,"");
			else
				hdn.value = hdn.value.replace(param+div,"");
		else
			hdn.value = hdn.value.replace(div+param,"");
	}

//*************************************************************************************************************************//
// remove caracteres indesejados de uma string
	function clearChars(str,charac,repl){
		var badChar = (charac != null) ? charac.charCodeAt(0) : 39;	// 39 = ';
		var newString = "";

		for (var i = 0; i < str.length; i++){
			if(str.charCodeAt(i) != badChar){
				newString += str.charAt(i);
			} else {
				if (repl != null)
					newString += repl;
			}
		}
		return newString;
	}

//*************************************************************************************************************************//
// Método que cria códigos numéricos, ex: entra 5287, sai 0000005287
	function addZero(str,nLoop){
		var nextVal = parseInt(str)+1;
		var size = nextVal.toString().length;
		var newStr = "";
		
		for(var i = 0; i < nLoop-size; i++){
			newStr += "0";
		}

		return newStr += nextVal.toString();
	}

//*************************************************************************************************************************//
// Método que cria códigos numéricos, ex: entra 5287, sai 0000005287
	function addZeroAssem(str,nLoop){
		var nextVal = parseInt(str);
		var size = nextVal.toString().length;
		var newStr = "";
		
		for(var i = 0; i < nLoop-size; i++){
			newStr += "0";
		}

		return newStr += nextVal.toString();
	}

//*****************************************************************************************************************************//
//método que exibe varias linhas ao mesmo tempo
//ex: trID = 22
//	  <tr id="tr_22_1">
//	  <tr id="tr_22_2">
//	  <tr id="tr_22_3">
	function showNLines(trID){
		var aTR = document.body.getElementsByTagName("TR");

		for (var i = 0; i < aTR.length; i++){
			if (aTR[i].id.indexOf(trID) == 0) aTR[i].style.display = (aTR[i].style.display == "none") ? "" : "none";
		}
	}
