// JavaScript

//*************************************************************************************************************************//
// Ativa / Desativa varios campos por vez em um formulario
	function habilitaCampos(act,campos,div,readOnly){
		var arrCampos = new Array();

		if (div == "") arrCampos[0] = campos;
		else arrCampos = campos.split(div);

		for (i = 0; i < arrCampos.length; i++){
			if (readOnly) document.getElementById(arrCampos[i]).readOnly = (act == 1) ? false : true;
			else document.getElementById(arrCampos[i]).disabled = (act == 1) ? false : true;
		}
	}

//*************************************************************************************************************************//
//método trim() em Javascript
	function trim(str){
	   return str.replace(/^\s*|\s*$/g,"");
	}

//***************************************************************************************************************
// formata textos com negrito, itático, sublinhado e outras coisas mais
	function changeSelection(tipo) {
		if (navigator.userAgent.indexOf("MSIE") > 0){
			var obj = document.selection.createRange();
			if (!obj.text) return;
			if (obj.parentElement().tagName != 'TEXTAREA') return;
			
			switch(tipo){
				case 1: obj.text = "<strong>" + obj.text + "</strong>"; break;
				case 2: obj.text = "<em>" + obj.text + "</em>"; break;
				case 3: obj.text = "<u>" + obj.text + "</u>"; break;
				case 4: obj.text = "<a href=# title=" + obj.text + ">" + obj.text + "</a>"; break;
				case 5: obj.text = "<font color=#003366>" + obj.text + "</font>"; break;
				case 6: obj.text = "<font color=#006633>" + obj.text + "</font>"; break;
				case 7: obj.text = "<font color=#660033>" + obj.text + "</font>"; break;
			}
		}
	}

//***************************************************************************************************************
// formata textos com negrito, itático, sublinhado
	function formatText(obj,tipo){
		switch(tipo){
			//Negrito
			case 1:
				var hdn = document.getElementById("hdnB");
				if(hdn.value == "0"){
					obj.value += "<strong>";
					hdn.value = 1;
				} else {
					obj.value += "</strong>";
					hdn.value = 0;
				}
			break;
			//Itálico
			case 2:
				var hdn = document.getElementById("hdnI");
				if(hdn.value == "0"){
					obj.value += "<em>";
					hdn.value = 1;
				} else {
					obj.value += "</em>";
					hdn.value = 0;
				}
			break;
			//Sublinhado
			case 3:
				var hdn = document.getElementById("hdnS");
				if(hdn.value == "0"){
					obj.value += "<u>";
					hdn.value = 1;
				} else {
					obj.value += "</u>";
					hdn.value = 0;
				}
			break;
		}

		obj.focus();
	}

//***************************************************************************************************************
// 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() + "/");
		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;
	}

//***************************************************************************************************************
// retorna a hora atual no formato: HH/MM/SS, sendo os segundos com exibição opcional
	function setCurrentTime(obj,sec){
		var hj = new Date();
		var novaHora = (hj.getHours() < 10) ? ("0" + hj.getHours() + ":") : (hj.getHours() + ":");
		novaHora += (hj.getMinutes() < 10) ? ("0" + hj.getMinutes()) : hj.getMinutes();
		if (sec) novaHora += (hj.getSeconds() < 10) ? (":0" + hj.getSeconds()) : (":" + hj.getSeconds());

		obj.value = novaHora;
	}

//***************************************************************************************************************
// - Método padrão que gera uma máscara automático em um campo tipo data
	function dateMask(local,string){
		onlyChars('0123456789');

		if(string.length == 2 ) local.value += "/";
		if(string.length == 5 ) local.value += "/";
	}

//***************************************************************************************************************
// - Método padrão que gera uma máscara automático em um campo tipo data
	function hourMask(local,string){
		onlyChars('0123456789');

		if(string.length == 2 ) local.value += ":";
		if(string.length == 5 ) local.value += ":00";
	}

//*****************************************************************************************************************************//
//aumenta o tamanho da tabela do menu para q ela fiquei do mesmo tamanho da tabela do sistema, seja qual for o tamanho
	function adjustMenu(){
		document.getElementById("menuTable").style.height = document.getElementById("contentTable").clientHeight  + "px";
	}

//*****************************************************************************************************************************//
//ajusta o sistema para centralizar na altura
	function setMiddle(){
		var hdt = (navigator.userAgent.indexOf("MSIE") > 0) ? getScreenHeight() - 190 : getHeight();
		var externalTable = document.getElementById("externalTable").clientHeight;
		var internalLine = document.getElementById("internalLine");
	
		if (hdt < externalTable) hdt = externalTable + 2;
	
		internalLine.height = parseInt((hdt - externalTable) / 2);
	}

//*****************************************************************************************************************************//
	function showLine(input){
		var line = document.getElementById(input);
		line.style.display = (line.style.display == "") ? "none" : "";
	}

//*****************************************************************************************************************************//
	// - Método que cria o padrão currency
	function formatNumber(str,len){
		var newStr = str;
		if (newStr.indexOf(",") != -1) newStr = newStr.replace(".","").replace(",",".");

		if (newStr.indexOf(".") == -1){
			newStr += ".00";
		} else {
			newStr = newStr.split(".")[0];
			var piece = (str.split(".")[str.split(".").length - 1]).substring(0,len);
			newStr += "." + ((parseInt(piece) < 10 && piece.indexOf("0") == -1) ? "0" + piece : piece);
		}

		return newStr;
	}

//*****************************************************************************************************************************//
	// - 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 getWidth(){
		var wWidth = 0;
		if (navigator.userAgent.indexOf("MSIE") > 0) {
			wWidth = document.body.clientWidth;
			return wWidth;
		} else {
			wWidth = window.outerWidth;
			return wWidth;
		}
	}
	
//*****************************************************************************************************************************//
	function setNavWidth(width){
		if (navigator.userAgent.indexOf("MSIE") > 0) {
			document.body.clientWidth = width;
		} else
			window.outerWidth = width;
	}

//*****************************************************************************************************************************//
	function getHeight(){
		if (navigator.userAgent.indexOf("MSIE") > 0) {	
			return document.body.clientHeight;
		} else {
			return window.innerHeight;
		}
	}

//*****************************************************************************************************************************//
	function setNavHeight(height){
		if (navigator.userAgent.indexOf("MSIE") > 0) {	
			document.body.clientHeight = height;
		} else
			window.innerHeight = height;
	}


//*****************************************************************************************************************************//
	function getScreenWidth(){
		return screen.width;
	}

//*****************************************************************************************************************************//
	function getScreenHeight(){
		return screen.height;
	}

//*****************************************************************************************************************************//
	function getWindowSize() {
		if (navigator.userAgent.indexOf("MSIE") > 0) {
			var sSize = (document.body.clientWidth * document.body.clientHeight);
			return sSize;
		} else {                                                
			var sSize = (window.outerWidth * window.outerHeight);
			return sSize;
		}
		return;      
	}

//*************************************************************************************************************************//
// adiciona um ZERO a mais ao numero, ex: 4 -> 04
	function returnZero(nro){
		return (nro < 10) ? "0" + nro : nro;
	}

//***************************************************************************************************************
	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;
	}

//***************************************************************************************************************
	function getMonthName(month){
		switch(month){
			case 0: return "Janeiro"; break;
			case 1: return "Fevereiro"; break;
			case 2: return "Março"; break;
			case 3: return "Abril"; break;
			case 4: return "Maio"; break;
			case 5: return "Junho"; break;
			case 6: return "Julho"; break;
			case 7: return "Agosto"; break;
			case 8: return "Setembro"; break;
			case 9: return "Outubro"; break;
			case 10: return "Novembro"; break;
			case 11: return "Dezembro"; break;
		}
	}

//***************************************************************************************************************
// imprime os options dentro dos combos/selects/pulldown's, ou seja lá o que for
	function returnDates(origem){
		switch (origem){
			case "day":
				for (var i = 1; i <= getDaysOfMonth(currentMonth(),currentYear()); i++){
					if (i == currentDay())
						document.write("<option value='"+i+"' selected>"+i+"</option>");
					else
						document.write("<option value='"+i+"'>"+i+"</option>");
				}
			break;
			case "month":
				var newMonth = null;
				for (var i = 1; i <= 12; i++){
					newMonth = getMonthName(i-1);
					if (i-1 == currentMonth())
						document.write("<option value='"+i+"' selected>"+newMonth+"</option>");
					else
						document.write("<option value='"+i+"'>"+newMonth+"</option>");
				}
			break;
			case "year":
				for(var i = 2004; i <= currentYear(); i++){
					if (i == currentYear())
						document.write("<option value='"+i+"' selected>"+i+"</option>");
					else
						document.write("<option value='"+i+"'>"+i+"</option>");
				}
			break;
		}
	}

//*************************************************************************************************************************//
// remove caracteres indesejados de uma string
	function clearChars(str,charac,repl){
		var badChar = charac.charCodeAt(0);
		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 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){
		if(navigator.appName == "Netscape"){
			local.location.href = url;
		} else {
			local.location = url;
		}
	}

//*************************************************************************************************************************//
// método que restringe a digitacao para apenas certos dígitos
	function onlyChars(cadeia,e){
		if (e != null)
			var key = (event) ? event.keyCode : e.which;
		else
			var key = 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 (event) {
					event.keyCode = 0;
				} else
					e.which = 0;
			} else
				if (event) event.keyCode = 0;
		}
	}

//**********************************************************************************************************//
	// - Método que seta a cor do background e fonte
	// onMouseOut="mouseOut(this,'#FFFFFF');"
	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
	// onMouseOver="mouseOver(this,'#E9E0D0','pointer');"
	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 retorna o objeto BODY para os mais comuns navegadores
	function getBody(){
		if (document.compatMode && document.compatMode != "BackCompat"){
		   var oBody = document.documentElement;
		} else {
		   var oBody = document.body;
		}
		return oBody;
	}

//*****************************************************************************************************************************//
	// método que exibe as capas dos album cadastrados
	function showDivs(e,size,id,img,show,tDiff,lDiff){
		if (tDiff == null) tDiff = 0;
		if (lDiff == null) lDiff = 0;
		if (img == "") img = "divImage";
		var posx = 0;
		var posy = 0;
		if (!e) var e = event;
		if (e.pageX || e.pageY){
			posx = e.pageX;
			posy = e.pageY;
		} else if (e.clientX || e.clientY){
			posx = e.clientX + document.body.scrollLeft;
			posy = e.clientY + document.body.scrollTop;
		}

		// posx and posy contain the mouse position relative to the document
		// Do something with this information

		with (document){
			for (var i = 0; i < size; i++){
				getElementById([img+i]).style.display = "none";
			}

			if (show)
				with (getElementById([img+id]).style){
					left = posx - lDiff;
					top = posy + 18 - tDiff;
					display = "";
				}
		}
	}

//*************************************************************************************************************************//
// 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 verifica se o navegador é Opera para poder formatar os campos CEP
	function doFormat(origem){
		// se não for o navegador Opera
		if(navigator.userAgent.toLowerCase().indexOf('opera') == -1){
			if(origem.value.length == 5)
				origem.value += '-';
			
			onlyNumbers('0123456789');
		}
	}

//*****************************************************************************************************************************//
	// método que exibe as capas dos album cadastrados
	function showDivs(e,size,id,img,show,tDiff,lDiff){
		if (tDiff == null) tDiff = 0;
		if (lDiff == null) lDiff = 0;
		if (img == "") img = "divImage";
		var posx = 0;
		var posy = 0;
		if (!e) var e = event;
		if (e.pageX || e.pageY){
			posx = e.pageX;
			posy = e.pageY;
		} else if (e.clientX || e.clientY){
			posx = e.clientX + document.body.scrollLeft;
			posy = e.clientY + document.body.scrollTop;
		}

		// posx and posy contain the mouse position relative to the document
		// Do something with this information

		with (document){
			for (var i = 0; i < size; i++){
				getElementById([img+i]).style.display = "none";
			}

			if (show)
				with (getElementById([img+id]).style){
					left = posx - lDiff;
					top = posy + 18 - tDiff;
					display = "";
				}
		}
	}

//*************************************************************************************************************************//
// método que controla a entra das 2 funcoes abaixo para indentificar se deve inserir ou remover o valor do hidden
	function controlHdn(hdn,input,div){
		if (input.checked) fillHdn(hdn,input.value,div);
		else clearHdn(hdn,input.value,div);
	}

//*************************************************************************************************************************//
// 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 existir no final
			if (hdn.value.substring(hdn.value.length-(param.length + 1),hdn.value.length).indexOf(div + param) >= 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,"");
	}

