function turnOnImage(imageName) {
	eval("document." + imageName).src = eval(imageName + "On").src;
}
	
function turnOffImage(imageName) {
	eval("document." + imageName).src = eval(imageName + "Off").src;
}

function message(msg) {
		document.all("message").innerText = document.all("message").innerText + '\n' + ' - ' +  msg ;
	}
	
function ChangeStyle(obj,estilo){
		obj.style.fontWeight = estilo;
	}

function refresh()
{
	location.reload();
}

function statusSelected(name){
	var formulario = document.meuform;
	var flag = 0;
	var i = 1;
	while(i<=formulario[name].length){
		if(formulario[name].options[i-1].selected){
			flag = 1;
			i =  formulario[name].length;
		}
		i = i + 1;
	}
	
	if (flag==0){
		return false;
	} else {
		return true;
	}
}

function insereopt(origem,destino,mensagem) {
	var formulario = document.meuform;
	if(statusSelected(origem)){
		 var vetor_values = new Array();
		 var vetor_text = new Array(); 
		 var i=0;
		 var j=0;
		
		 	while (j < formulario[origem].length) {
				 if (formulario[origem].options[j].selected==true) {
		   				vetor_values[i]=formulario[origem].options[j].value;
		   				vetor_text[i]=formulario[origem].options[j].text;
		   				i++;
		  			} 
		  			j++;
		 	}
				
		 	for(i=0;i < vetor_values.length;i++) {
		  		formulario[destino].options[formulario[destino].options.length] = new Option(vetor_text[i], vetor_values[i], false, false);
			 }
	} else {
		message(mensagem);
	}
	
	
}

function checkform(nome)
	{
	   selectall(nome);
	};
	
function movedown(name) {
	var formulario = document.meuform;
	
	if(statusSelected(name)){
		 if ((formulario[name].length >= 2) && (formulario[name].options.selectedIndex != (formulario[name].length-1))) {
		  var item = formulario[name].options[formulario[name].options.selectedIndex];
		  var index = formulario[name].options.selectedIndex;  
		  var mats_src = new Array();
		  var aux;
		  var i=0;
		    for(i=0;i < formulario[name].length;i++) {
		   mats_src[i]=formulario[name].options[i];  
		    }
		  aux=mats_src[index+1];
		  mats_src[index+1]=item;
		  mats_src[index]=aux;
		  deleteall(name);
		    for(i=0;i < mats_src.length;i++) {
		     formulario[name].options[i] = new Option(mats_src[i].text,mats_src[i].value, false, false);  
		    }
		  formulario[name].options[index+1].selected=true;
		 } else {
		 	nd();
		 	document.all("message").innerText = '';
		 	message("Para mover, precisa existir pelo menos dois registros e um deles precisa estar selecionado, sem ser o último"); 
		 }
	} else {
		message('É preciso selecionar algum registro acima');
	}
	
}

function moveup(name) {
	var formulario = document.meuform;
	if(statusSelected(name)){
		 if ((formulario[name].length >= 2) && (formulario[name].options.selectedIndex > 0)) {
		  var item = formulario[name].options[formulario[name].options.selectedIndex];
		  var index = formulario[name].options.selectedIndex;  
		  var mats_src = new Array();
		  var aux;
		  var i=0;
		    for(i=0;i < formulario[name].length;i++) {
		   mats_src[i]=formulario[name].options[i];  
		    }
		  aux=mats_src[index-1];
		  mats_src[index-1]=item;
		  mats_src[index]=aux;
		  deleteall(name);
		    for(i=0;i < mats_src.length;i++) {
		     formulario[name].options[i] = new Option(mats_src[i].text,mats_src[i].value, false, false);  
		    }
		  formulario[name].options[index-1].selected=true;
		 
		 } else {
		 	nd();
		 	document.all("message").innerText = '';
			message("Para mover, precisa existir pelo menos dois registros e um deles precisa estar selecionado, sem ser o primeiro"); 
		 }
 
	 } else {
			message('É preciso selecionar algum registro acima');
		}
}

function deselectall(name){
	 	var formulario = document.meuform;
	 		var i=0;
	 		for(i=0;i < formulario[name].length;i++)
	 			{
	    		formulario[name].options[i].selected=false;
	 			};
		};
	 
	function selectall(name)
	{
		var formulario = document.meuform;
	   var i=0;
	   for(i=0;i < formulario[name].length;i++)
	   {
	      formulario[name].options[i].selected=true;
	   };
	};
	 
	function deleteopt(nome)
	{
		var formulario = document.meuform;
		if(statusSelected(nome)){
			var i=0;
		   while((formulario[nome].selectedIndex != -1) && (i < 100))
		   {
		      formulario[nome].options[formulario[nome].selectedIndex] = null;
		      i++;
		   }
		} else {
			message('É preciso selecionar alguma validação acima');
		}
	};
	 
	function deleteall(nome)
	{
		var formulario = document.meuform;
	   var i=0;
	   while(formulario[nome].length != 0)
	   {
	      i=formulario[nome].length;
	      i=i-1;
	      formulario[nome].options[i].selected=true;      
	      formulario[nome].options[formulario[nome].selectedIndex] = null;      
	   }
	};

/*
	'[======================================================================================
	'[= Nome		: DeBlockChar
	'[= Autor		: Fabio Silva Lima (Broker)
	'[= Descrição	: Bloqueia caracteres a partir de uma string.
	'[= Entrada		: strForm   - string nova ou pré-definida.
	'[= Saida		: Bloqueia caracter
	'[======================================================================================
	*/
	function DeBlockChar(strForm){
	var obj = String.fromCharCode(event.keyCode);
	var str1 = "0123456789";
	var str2 = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
	var str3 = ".@_-";
	var str4 = ",";
	var str5 = " ";
	var str = str1 + str2 + str5;
	if (strForm!='0'){
		if (strForm=='numeros'){
			str = str1;
		} else {
			if (strForm=='letras'){
				str = str2;
			} else {
				if (strForm=='numeroseletras'){
					str = str1 + str2;
				} else {
					if (strForm=='email'){
						str = str1 + str2 + str3;
					} else {
						if (strForm=='espaco'){
							str = str5;
						} else {
							if (strForm=='decimal'){
								str = str1 + str4;
							} else {
								str = strForm;
							}
						}
					}		
				}	
			}
		}
	}
	var flag = 0;
	for (i = 0; i < str.length; i++) {
		if (obj==str.charAt(i)){
			flag = 1;
		} 
	}
	
	if (flag==1){
		event.returnValue = true;
			return;
	} else {
		event.returnValue = false;
			return;
	}
}
		
/*
'[======================================================================================
'[= Nome		: IsEmpty
'[= Descrição	: Verifica se uma string está vazia ou somente com caracteres nulos
'[= Entrada		: psString 
'[= Saida		: True  - se a string estiver vazia
'[=				  False - caso contrário
'[= OBS			:	
'[======================================================================================
*/
function IsEmpty(psString)
{
	/*
	** Caracteres Inválidos
	*/
	var lsTab   = '\t', // Tab Char
		lsSpace = ' ' , // Space
        lsCRLF  = '\n', // CR LF
		lsCR    = '\r'; // CR
	
	/*
	** Procura por caracteres válidos
	*/
	for (var liPos = 0; liPos < psString.length; liPos++)
	{
		var lsChar = psString.charAt(liPos);
		if (lsChar != lsTab   &&
			lsChar != lsSpace && 
			lsChar != lsCRLF  && 
			lsChar != lsCR )
			return (false);
	}
	
	return (true);
}

/*
	'[======================================================================================
	'[= Nome		: BlockChar
	'[= Autor		: Fabio Silva Lima (Broker)
	'[= Descrição	: Bloqueia caracteres a partir de uma string.
	'[= Entrada		: strForm   - string nova ou pré-definida.
	'[= Saida		: Bloqueia caracter
	'[======================================================================================
	*/
	function BlockChar(strForm){
	var obj = String.fromCharCode(event.keyCode);
	var str1 = "0123456789";
	var str2 = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
	var str3 = ".@_-";
	var str4 = ",";
	var str5 = " ";
	var str = str1 + str2 + str5;
	if (strForm!='0'){
		if (strForm=='numeros'){
			str = str1;
		} else {
			if (strForm=='letras'){
				str = str2;
			} else {
				if (strForm=='numeroseletras'){
					str = str1 + str2;
				} else {
					if (strForm=='email'){
						str = str1 + str2 + str3;
					} else {
						if (strForm=='espaco'){
							str = str5;
						} else {
							if (strForm=='decimal'){
								str = str1 + str4;
							} else {
								str = strForm;
							}
						}
					}		
				}	
			}
		}
	}
	var flag = 0;
	for (i = 0; i < str.length; i++) {
		if (obj==str.charAt(i)){
			flag = 1;
		} 
	}
	
	if (flag==1){
		event.returnValue = true;
			return;
	} else {
		event.returnValue = false;
			return;
	}
}

function mostra(item){
if (item.style.display=='none'){
item.style.display='';
}
else{
item.style.display='none'
}
}

/*
'[======================================================================================
'[= Nome		: SplitString
'[= Descrição	: Divide a string por um separador dado, retornando um array com os valores.
'[= Entrada		: psString  - String a ser dividida
'[=               psDivider - Divisor
'[= Saida		: Array com os items
'[= OBS			:	
'[======================================================================================
*/
function SplitString(psString, psDivider)
{
	/*
	** Conta o número de ocorrências do separador para saber quantos elementos terá o Array.
	*/
	var liOccurs = 0;
	
	for (var liCount = 0; liCount < (psString.length - psDivider.length); liCount++)	
		if (psString.substr(liCount, psDivider.length) == psDivider)
			liOccurs++;
			
	/*
	** Cria o array
	*/
	var laRet = new Array(liOccurs);
	var lsAux = '';
	
	liCount  = 0;
	liOccurs = 0;
	do
	{
		if (psString.substr(liCount, psDivider.length) == psDivider)
		{
			liCount += psDivider.length;
			laRet[liOccurs++] = lsAux;
			lsAux = '';
		}
		
		lsAux += psString.charAt(liCount++);
	}
	while (liCount < psString.length);
	
	laRet[liOccurs++] = lsAux;
	
	return (laRet);
}

/*
'[======================================================================================
'[= Nome		: Replace
'[= Descrição	: Pesquisa a string psSearch dentro da string psText, trocando por psReplace
'[= Entrada		: psText    - String a ser pesquisada
'[=               psSearch  - String a ser localizada
'[=				  psReplace - String a ser colocada no lugar de psSearch
'[= Saida		: String com psSearch trocada por psReplace
'[= OBS			:	
'[======================================================================================
*/
function Replace(psText, psSearch, psReplace)
{
	//alert('psText : ' + psText);
	//alert('psSearch : ' + psSearch);
	//alert('psReplace : ' + psReplace);
	var liLen   = psSearch.length;
	var liPos   = psText.indexOf(psSearch);
	var lsLeft  = '';
	var lsRight = '';
	        
	while (liPos > (-1))
	{
		lsLeft  = psText.substring(0, liPos);
		lsRight = psText.substring(liPos + liLen , psText.length);
		psText  = lsLeft + psReplace + lsRight;
		liPos   = psText.indexOf(psSearch);
	}
	        
	return (psText);
}

function popup(url,width,height,scroll,resize,full) {
	if (scroll==1) scroll='yes'; else scroll='no';
	if (full==1) full='yes'; else full='no';
	if (resize==1) resize='yes'; else resize='no';
	var str='fullscreen='+full+',scrollbars='+scroll+',status=no,menubar=no,resizable='+resize+',width='+width+',height='+height+''
	window.open(url,'',str);
	return false;	
}

function ShowHideObject(param,obj){
	var objeto = document.getElementById(obj);
		if (param=='hide'){
			objeto.style.visibility = "hidden";
			objeto.style.position = "absolute";
		} else {
			objeto.style.visibility = "visible";
			objeto.style.position = "relative";
		}
}

function Paste(theField){
	var tempval=eval("document."+theField);
	tempval.focus();
	therange=tempval.createTextRange();
	therange.execCommand("Paste");
}

/*
'[======================================================================================
'[= Nome		: IsDate
'[= Descrição	: Verifica se uma string é uma data válida
'[= Entrada		: psData - String de data no formato DD/MM/YYYY
'[= Saida		: True  - se a string for uma data
'[=				  False - caso contrário
'[= OBS			:
'[======================================================================================
*/
function IsDate(psData)
{
	var laDiasMes = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
	var laData    = SplitString(psData, '/');

	/*
	** Se não houver três partes a data é considerada inválida
	*/
	if (laData.length != 3)
		return false;
	
	/*
	** A string é dividida em três partes :
	**
	** laData[0] - Dia
	** laData[1] - Mês
	** laData[2] - Ano
	*/

	/*
	** Verifica se o mes está no intervalo [1,12]
	*/
	if (!(laData[1] >= 1 && laData[1] <= 12))
		return false;

	/*
	** Se o ano não tiver 4 digitos ou se é maior que 2000 e menor que 2100, é invalida
	*/
	if (laData[2].length != 4) 
		return false;
	
	if (!(laData[2] >= 1900 && laData[2] <= 2500))
		return false;
	/*
	** Se for ano bissexto, o Limite p/ o mes de Fevereiro é 29 dias
	*/
	if (Math.floor(laData[2] / 4) * 4 == laData[2]) 
		laDiasMes[1] = 29;

	/*
	** Verifica se cada parte eh um numero POSITIVO
	*/
	for(var i = 0; i < laData.length; i++)
	{
		if (IsEmpty(laData[i]))
			return (false);
		if (!IsNumber(laData[i]))
			return (false)
		else if (parseFloat(laData[i]) < 0)
			return (false);
	}

	/*
	** Se o dia estiver fora do limite para o mes dado, é invalida
	*/
	if (!((laData[0] >= 1) && (laData[0] <= laDiasMes[laData[1] - 1])))
		return (false);

	/*
	** Finalmente, se chegou até aqui, é uma data válida
	*/
	return (true);
}

/*
'[======================================================================================
'[=	FUNÇÕES DE VALIDAÇÃO DE DADOS
'[======================================================================================
*/

/*
'[======================================================================================
'[= Nome		: IsNumber
'[= Descrição	: Verifica se uma string é um número.
'[= Entrada		: psNumber
'[= Saida		: True  - se a string for um número
'[=				  False - caso contrário
'[= OBS			:	
'[======================================================================================
*/
function IsNumber(psNumber)
{
	var InvalidChar = IsEmpty(psNumber);
	
	for (var i = 0; i < psNumber.length; i++)
	{
		var Char = psNumber.charAt(i);
		if (Char != "." && Char != "," && Char != "-")
			if (isNaN(parseInt(Char)))
				InvalidChar = true  || InvalidChar
			else
				InvalidChar = false || InvalidChar;
	}
	
	return (!InvalidChar);
}

function ValidaAlfa(nome)
{
	cadeia=" AÁÃBCÇDEÉFGHIÍJKLMNOÓÔÕPQRSTUÚVWXYZaãábçcdeéfghiíjklmnoóôõpqrstuúvxwzyz0123456789,.-"
	for (i=0;i<nome.length;i++)
	{
		if (cadeia.indexOf(nome.substring(i,i+1)) == -1)
		{return false;}
	}
	return true;
}

function IsEmail (email)
{
	var intPosCarac = email.indexOf("@")
	if(intPosCarac == -1)
		return false;
	else
	{
		var strDepois = email.substr(intPosCarac+1,email.length-intPosCarac)
		var strAntes = email.substr(0,intPosCarac)
		intPosCarac = strDepois.indexOf(".")

		if (strAntes.charAt(strAntes.length-1) == ".") {
			return false;
		}

		for (i = 0; i < email.length; i++) {   
        		var c = email.charAt(i);
        		if (c == " ") {
        			return false;
        		}
    		}
    		
    		if (email.length == email.lastIndexOf(".con") + 4) {
    			return false;
    		}
    		if (email.length == email.lastIndexOf(".con.br") + 7) {
    			return false;
    		}
    		if (email.length == email.lastIndexOf(".com.b") + 6) {
    			return false;
    		}
    		if (email.lastIndexOf("www.") != -1) {
    			return false;
    		}
    		
    		
    		

		if(intPosCarac==-1)
			return false;
		else
		{
			while(intPosCarac != -1)
			{
				if(strAntes=="" || strAntes=="." || strDepois=="." ||(!ValidaAlfa(strDepois)) || (!ValidaAlfa(strAntes)))
					return false;
				else
				{
					strDepois = strDepois.substr(intPosCarac+1,strDepois.length-intPosCarac)
					strAntes = strDepois.substr(0,intPosCarac)
					if(strAntes=="" || (!ValidaAlfa(strDepois)) || (!ValidaAlfa(strAntes)))
						return false;
				}
				intPosCarac = strDepois.indexOf(".")
			}
			return true;
		}
	}
}


function cOn(td,cor){
if(document.getElementById||(document.all && !(document.getElementById))){
td.style.backgroundColor=cor;
}
}

function cOut(td,cor){
if(document.getElementById||(document.all && !(document.getElementById))){
td.style.backgroundColor=cor;
}
}

function hL(E,cor){
	while (E.tagName!="TR")
		{E=E.parentElement;}
		E.style.backgroundColor=cor;
}

function dL(E,cor){

while (E.tagName!="TR")
	{E=E.parentElement;}
	E.style.backgroundColor=cor;
}


function CCA(CB,cor1,cor2){
if (CB.checked)
	hL(CB,cor1);
else
	dL(CB,cor2);
}

function isEmail (email)
{
	var intPosCarac = email.indexOf("@")
	if(intPosCarac == -1)
		return false;
	else
	{
		var strDepois = email.substr(intPosCarac+1,email.length-intPosCarac)
		var strAntes = email.substr(0,intPosCarac)
		intPosCarac = strDepois.indexOf(".")

		if (strAntes.charAt(strAntes.length-1) == ".") {
			return false;
		}

		for (i = 0; i < email.length; i++) {   
        		var c = email.charAt(i);
        		if (c == " ") {
        			return false;
        		}
    		}
    		
    		if (email.length == email.lastIndexOf(".con") + 4) {
    			return false;
    		}
    		if (email.length == email.lastIndexOf(".con.br") + 7) {
    			return false;
    		}
    		if (email.length == email.lastIndexOf(".com.b") + 6) {
    			return false;
    		}
    		if (email.lastIndexOf("www.") != -1) {
    			return false;
    		}
    		
    		
    		

		if(intPosCarac==-1)
			return false;
		else
		{
			while(intPosCarac != -1)
			{
				if(strAntes=="" || strAntes=="." || strDepois=="." ||(!ValidaAlfa(strDepois)) || (!ValidaAlfa(strAntes)))
					return false;
				else
				{
					strDepois = strDepois.substr(intPosCarac+1,strDepois.length-intPosCarac)
					strAntes = strDepois.substr(0,intPosCarac)
					if(strAntes=="" || (!ValidaAlfa(strDepois)) || (!ValidaAlfa(strAntes)))
						return false;
				}
				intPosCarac = strDepois.indexOf(".")
			}
			return true;
		}
	}
}