/*
================================================================================================
AUTOR:		RAFAEL DE BRITO FISCHER
DATA:		30/04/2005
DESCRICAO:	FUNCAO PARA VERIFICAR OS CAMPOS OBRIGATORIOS DOS FORMULARIO
EXEMPLO:	NO FORMULARIO -> onSubmit="javascript: return verificaCampo(this);"
			INSERIR EM CADA CAMPO QUE SERA VALIDADO: <input ... valor="Tipo de Validacao|Descricao do campo que irá aparecer no alerta" >
			NOS CAMPOS DO FORMULARIO OBRIGATORIOS INSERIR OS SEGUINTES "TIPOS DE VALIDACOES": 
			* PARA VALIDAR SE UM CAMPO COM TEXTO NORMAL COMO OBRIGATORIO EH VALIDO, INSERIR valor="*|Descricao"
			* PARA VALIDAR SE UM CAMPO EH UM EMAIL VALIDO, COLOCAR AO INVES DE *, INSERIR valor="EMAIL|Descricao", EM MAIUSCULO
			* PARA VALIDAR SE UM CAMPO EH SOMENTE NUMERICO, COLOCAR AO INVES DE *, INSERIR valor="NUMERO|Descricao", EM MAIUSCULO
================================================================================================
*/
var strMsg = '';
var objCampoFocus = undefined;

function verificaCampo(frmFormulario){
	var intCont, objCampo, arrValor, intContCampo;
	for(intCont = 0; intCont < frmFormulario.elements.length; intCont++){
		objCampo = frmFormulario.elements[intCont];
		if(objCampo.valor != null && objCampo.valor != undefined){
			arrValor = objCampo.valor.split('|');
			if(objCampo.type == 'text' || objCampo.type == 'password' || objCampo.type == 'hidden' || objCampo.type == 'file' || objCampo.type == 'textarea'){
				if(arrValor[0] == '*'){
					if(objCampo.value.trim() == ''){
						strMsg += '- ' + arrValor[1] + '\n';

						if(objCampoFocus == undefined)
							objCampoFocus = objCampo;
					}
				}
				else if(arrValor[0] == 'OPCIONAL_UM'){
					var objGrupo = objCampo.grupo;
					if(objGrupo != null && objGrupo != undefined){
						for(intContCampo = 0; intContCampo < objCampo.length; intContCampo++){
							objCampo = objCampo[intContCampo];
							if(objCampo.grupo != null && objCampo.grupo != undefined){
								if(objGrupo.trim() == objCampo.grupo.trim()){
									if(objCampo.value.trim() == ''){
										strMsg += '- ' + arrValor[1] + '\n';

										if(objCampoFocus == undefined)
											objCampoFocus = objCampo;
										break;
									}
								}
							}
							else{
								strMsg += '! É necessário expecificar a propriedade \"grupo\" para os campos que sejam opcionais.';
								break;
							}
						}
					}
				}
				else if(arrValor[0] == 'EMAIL'){
					if(objCampo.value.trim() == '' || (!objCampo.value.trim().isEmail())){
						strMsg += '- Campo ' + arrValor[1] + ' não é um campo de e-mail válido\n';

						if(objCampoFocus == undefined)
							objCampoFocus = objCampo;
					}
				}
				else if(arrValor[0] == 'NUMERO'){
					if(objCampo.value.trim() == ''){
						strMsg += '- ' + arrValor[1] + '\n';
						
						if(objCampoFocus == undefined)
							objCampoFocus = objCampo;
						continue;
					}
					if(!objCampo.value.trim().isNumber()){
						strMsg += '- Campo ' + arrValor[1] + ' não é um campo numérico válido\n';

						if(objCampoFocus == undefined)
							objCampoFocus = objCampo;
					}
				}
				else if(arrValor[0] == 'NUMERO_OPCIONAL'){
					if(!objCampo.value.trim()){
						if(!objCampo.value.trim().isNumber()){
							strMsg += '- Campo ' + arrValor[1] + ' não é um campo numérico válido\n';

							if(objCampoFocus == undefined)
								objCampoFocus = objCampo;
						}
					}
				}
				else if(arrValor[0] == 'REPETESENHA'){
					if(objCampo.value.trim() == '' || (objCampo.value.trim() != eval(arrValor[1]).value.trim())){
						strMsg += '- Campo ' + arrValor[2] + ' não é semelhante ao campo de senha\n';

						if(objCampoFocus == undefined)
							objCampoFocus = objCampo;
					}
				}
				else if(arrValor[0] == 'CPF_CNPJ'){
					var intIndiceRadioSelec = null;
					var objOption = frmFormulario.optPessoa;
					for(i = 0; i < objOption.length; i++){
						if(objOption[i].checked){
							intIndiceRadioSelec = i;
							break;
						}
					}
					if(intIndiceRadioSelec != null){
						if(objOption[intIndiceRadioSelec].tipo == 'Fisica'){
							if(!objCampo.value.trim().isCPF()){
								strMsg += '- Número não é um campo CPF válido\n';
								if(objCampoFocus == undefined)
									objCampoFocus = objCampo;
							}
						}
						else if(objOption[intIndiceRadioSelec].tipo == 'Juridica'){
							if(!objCampo.value.trim().isCNPJ()){
								strMsg += '- Número não é um campo CNPJ válido\n';					
								if(objCampoFocus == undefined)
									objCampoFocus = objCampo;
							}
						}
					}
				}
				else if(arrValor[0] == 'CPF'){
					if(!objCampo.value.trim().isCPF()){
						strMsg += '- Número não é um campo CPF válido\n';
						if(objCampoFocus == undefined)
							objCampoFocus = objCampo;
					}
				}
				else if(arrValor[0] == 'CNPJ'){
					if(!objCampo.value.trim().isCNPJ()){
						strMsg += '- Número não é um campo CNPJ válido\n';					
						if(objCampoFocus == undefined)
							objCampoFocus = objCampo;
					}
				}
				else if(arrValor[0] == 'CEP'){
					if(objCampo.value.trim() == '' || (!objCampo.value.trim().isCEP())){
						strMsg += '- ' + arrValor[1] + '\n';

						if(objCampoFocus == undefined)
							objCampoFocus = objCampo;
					}
				}
			}
			else if(objCampo.type == 'radio'){
				if(arrValor[0] == 'RADIO'){
					var objRadio = null;
					for(i = 0; i < frmFormulario.elements.length; i++){
						if(frmFormulario.elements[i].type == 'radio'){
							if(frmFormulario.elements[i].name == objCampo.name){
								if(frmFormulario.elements[i].checked){
									objRadio = null;
									break;
								}
								else{
									if(objRadio == null){
										objRadio = frmFormulario.elements[i];
									}
								}
							}
						}
					}
					if(objRadio != null){
						strMsg += '- '+ arrValor[1] +'\n';
						if(objCampoFocus == undefined)
							objCampoFocus = objCampo;
					}
				}
			}
			else if(objCampo.type == 'checkbox'){
				if(arrValor[0] == 'CHECKBOX'){
					var objCheckBox = null;
					for(i = 0; i < frmFormulario.elements.length; i++){
						if(frmFormulario.elements[i].type == 'checkbox'){
							if(frmFormulario.elements[i].checked){
								objCheckBox = null;
								break;
							}
							else{
								if(objCheckBox == null){
									objCheckBox = frmFormulario.elements[i];
								}
							}
						}
					}
					if(objCheckBox != null){
						strMsg += '- '+ arrValor[1] +'\n';
						if(objCampoFocus == undefined)
							objCampoFocus = objCampo;
					}
				}
			}			
			else if(objCampo.type == 'select-one'){
				if(arrValor[0] == 'COMBO'){
					if(objCampo.selectedIndex == 0){
						strMsg += '- '+ arrValor[1] +'\n';					
						if(objCampoFocus == undefined)
							objCampoFocus = objCampo;
					}
				}
			}
		}
	}
	if(strMsg != ''){
		return false;
	}
	return true;
}


/*
================================================================================================
AUTOR:		RAFAEL DE BRITO FISCHER
DATA:		01/05/2005
DESCRICAO:	FUNCAO PARA RETIRAR OS ESPAÇOS EM BRANCO DA ESQUERDA E DA DIREITA DA STRING
EXEMPLO:	NO FORMULARIO -> variavelString.trim()
================================================================================================
*/
String.prototype.trim = function() {
	return this.replace(/^\s*(.*)/, "$1").replace(/(.*?)\s*$/, "$1");
}


/*
================================================================================================
AUTOR:		RAFAEL DE BRITO FISCHER
DATA:		01/05/2005
DESCRICAO:	FUNCAO PARA VALIDAR SE UMA STRING EH UM E-MAIL VALIDO
EXEMPLO:	NO FORMULARIO -> variavelString.isEmail()
================================================================================================
*/
String.prototype.isEmail = function() {
	return (this.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1);
}


/*
================================================================================================
AUTOR:		RAFAEL DE BRITO FISCHER
DATA:		01/05/2005
DESCRICAO:	FUNCAO PARA VALIDAR SE UMA STRING EH UM NUMERO VALIDO
EXEMPLO:	NO FORMULARIO -> variavelString.isNumber()
================================================================================================
*/
String.prototype.isNumber = function() {
	var strRetiraCaracEspec = this;
	strRetiraCaracEspec = strRetiraCaracEspec.replace('-', '');
	strRetiraCaracEspec = strRetiraCaracEspec.replace('/', '');
	strRetiraCaracEspec = strRetiraCaracEspec.replace('.', '');
	return (!isNaN(strRetiraCaracEspec));
}


/*
================================================================================================
AUTOR:		RAFAEL DE BRITO FISCHER
DATA:		01/07/2005
DESCRICAO:	FUNCAO PARA VALIDAR SE UMA STRING EH UM CEP
EXEMPLO:	NO FORMULARIO -> variavelString.isCEP()
================================================================================================
*/
String.prototype.isCEP = function() {
	return (!isNaN(this));
}


/*
================================================================================================
AUTOR:		RAFAEL DE BRITO FISCHER
DATA:		28/06/2005
DESCRICAO:	FUNCAO PARA VALIDAR SE UMA STRING EH UM NUMERO DE CNPJ
EXEMPLO:	NO FORMULARIO -> variavelString.isCNPJ()
================================================================================================
*/
String.prototype.isCNPJ = function() {
	var i;
	s = this
	var c = s.substr(0,12);
	var dv = s.substr(12,2);
	var d1 = 0;
	for (i = 0; i < 12; i++){
		d1 += c.charAt(11-i)*(2+(i % 8));
	}
	if (d1 == 0) 
		return false;
	d1 = 11 - (d1 % 11);
	if (d1 > 9) 
		d1 = 0;
	if (dv.charAt(0) != d1){
		return false;
	}

	d1 *= 2;
	for (i = 0; i < 12; i++){
		d1 += c.charAt(11-i)*(2+((i+1) % 8));
	}
	d1 = 11 - (d1 % 11);
	if (d1 > 9) 
		d1 = 0;
	if (dv.charAt(1) != d1){
		return false;
	}
	return true;
}


/*
================================================================================================
AUTOR:		RAFAEL DE BRITO FISCHER
DATA:		28/06/2005
DESCRICAO:	FUNCAO PARA VALIDAR SE UMA STRING EH UM NUMERO DE CPF
EXEMPLO:	NO FORMULARIO -> variavelString.isCPF()
================================================================================================
*/
String.prototype.isCPF = function() {
	cpf = this;
	erro = new String;
	if (cpf.length < 11) 
		return false;
	var nonNumbers = /\D/;
	if (nonNumbers.test(cpf)){
		return false;
	}
	if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){
		return false;
	}
	var a = [];
	var b = new Number;
	var c = 11;
	for (i=0; i<11; i++){
		a[i] = cpf.charAt(i);
		if (i < 9) 
			b += (a[i] * --c);
	}
	if ((x = b % 11) < 2) {
		a[9] = 0;
	}
	else {
		a[9] = 11-x;
	}
	b = 0;
	c = 11;
	
	for (y=0; y<10; y++) 
		b += (a[y] * c--); 

	if ((x = b % 11) < 2) {
		a[10] = 0;
	}
	else{
		a[10] = 11-x;
	}

	if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
		return false;
	}

	return true;
}

function validaFormulario(frmFormulario){
	strMsg = '';
	objCampoFocus = undefined;
	var blnRetorno = verificaCampo(frmFormulario);

	if(strMsg != ''){
		alert('Por favor preencha corretamente os campos:\n\n' + strMsg);
		if(objCampoFocus.type != 'hidden')
			objCampoFocus.focus();
	}
	return (blnRetorno);
}

function selecionarTudo(objCheckBox, blnSelecionado){
	var chkListaGrupo = eval("document.forms[0]." + objCheckBox);
	if(chkListaGrupo != undefined){
		if(chkListaGrupo.length != undefined){
			for(var i = 0; i < chkListaGrupo.length; i++){
				chkListaGrupo[i].checked = blnSelecionado;
			}
		}
		else{
			chkListaGrupo.checked = blnSelecionado;
		}
	}
	return false;
}

function confirmar(){
	return confirm('Deseja realmente excluir o(s) item(s) selecionado(s) ?');
}

function confirmarExclusao(URL, ComplementoItem, IDRegistro, Registro){
	if(confirm('Deseja realmente excluir o '+ ComplementoItem +': '+ Registro +' ?')){
		document.location.href = URL + '?ID='+ IDRegistro;
	}
}

function mudarImagem(objBotao, Imagem){
	objBotao.src = '../images/' + Imagem;
}

function clickUrlBotao(strUrl, strTarget){
	eval((strTarget != '' ? strTarget + '.' : '') + document.location.replace(strUrl));
}

function formatarCampo(Campo, Mascara, CaracterMascara){
	var intContador = Campo.value.length;
	var conteudoCampo = Mascara.substring(intContador);
	if (conteudoCampo.substring(0, 1) != CaracterMascara){
		Campo.value += conteudoCampo.substring(0, 1);
	}
}

function fecharJanela(objJanela){
	eval(objJanela + '.close();');
}

// OPTIONS DINAMICOS			
function addOption(theSel, theText, theValue){
	var newOpt = new Option(theText, theValue);
	var selLength = theSel.length;
	theSel.options[selLength] = newOpt;
}

function deleteOption(theSel, theIndex){ 
	var selLength = theSel.length;
	if(selLength > 0){
		theSel.options[theIndex] = null;
	}
}

function moveOptions(theSelFrom, theSelTo){
	theSelFrom = document.getElementById(theSelFrom);
	theSelTo = document.getElementById(theSelTo);
	var selLength = theSelFrom.length;
	var selectedText = new Array();
	var selectedValues = new Array();
	var selectedCount = 0;				  
	var i;

	for(i=selLength-1; i >= 0; i--){
		if(theSelFrom.options[i].selected){
			selectedText[selectedCount] = theSelFrom.options[i].text;
			selectedValues[selectedCount] = theSelFrom.options[i].value;
			deleteOption(theSelFrom, i);
			selectedCount++;
		}
	}

	for(i = selectedCount-1; i >= 0; i--){
		addOption(theSelTo, selectedText[i], selectedValues[i]);
	}
}

function moveOptionsAll(theSelFrom, theSelTo){			  
	for(var i = 0; i < document.getElementById(theSelFrom).length; i++){
		document.getElementById(theSelFrom).options[i].selected = true;
	}
	moveOptions(theSelFrom, theSelTo);
}

function isTamanhoValido(Texto, tamanhoMinimo, tamanhoMaximo){
	var blnOk = false;
	if(Texto != null && Texto != undefined){
		var strTexto = Texto.trim();
		var intTamanhoTexto = strTexto.length;
		if((intTamanhoTexto >= tamanhoMinimo) && (intTamanhoTexto <= (tamanhoMaximo == -1 ? intTamanhoTexto : tamanhoMaximo))){
			blnOk = true;
		}
	}

	return blnOk;
}

function charCode(evt){
	if(evt.keyCode < 48 || evt.keyCode > 57){
		return false;
	}
}

function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }

  function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }

function fadein(objMouseOver, idDivTransicao, codigoTransicao){
	var args = fadein.arguments;
	var divTransicao = _$(idDivTransicao);
	var intDiferenca = 0;
	var intDuracao = 1;
	if(objMouseOver && divTransicao){
		intPosicaoTopInicial = findPosY(objMouseOver);
		intPosicaoLeftInicial = findPosX(objMouseOver);
		intDiferenca = (args.length > 3 ? args[3] : intDiferenca);
		intDuracao = (args.length > 4 ? args[4] : intDuracao);

		divTransicao.style.top = intPosicaoTopInicial;
		divTransicao.style.left = intPosicaoLeftInicial-intDiferenca;
		divTransicao.filters.revealTrans.apply();
		divTransicao.filters.revealTrans.Transition = codigoTransicao;
		divTransicao.filters.revealTrans.Duration = intDuracao;
		divTransicao.style.visibility = 'visible';
		divTransicao.filters.revealTrans.play();
	}
}

function fadeout(objMouseOut, idDivTransicao, codigoTransicao){
	var args = fadeout.arguments;
	var divTransicao = _$(idDivTransicao);
	var intDiferenca = 0;
	var intDuracao = 2;
	if(objMouseOut && divTransicao){
		intPosicaoTopInicial = findPosY(objMouseOut);
		intPosicaoLeftInicial = findPosX(objMouseOut);
		intDiferenca = (args.length > 3 ? args[3] : intDiferenca);
		intDuracao = (args.length > 4 ? args[4] : intDuracao);

		divTransicao.style.top = intPosicaoTopInicial;
		divTransicao.style.left = intPosicaoLeftInicial-intDiferenca;
		divTransicao.filters.revealTrans.apply();
		divTransicao.filters.revealTrans.Transition = codigoTransicao;
		divTransicao.filters.revealTrans.Duration = intDuracao;
		divTransicao.style.visibility = 'hidden';
		divTransicao.filters.revealTrans.play();
	}	
}

function verificaTempoTimeOutBanner(tempoDuracao, posicao){
	var args = verificaTempoTimeOutBanner.arguments;
	var intDiferenca = 350;
	var dblDuracao = 0.2;
	intDiferenca = (args.length > 2 ? args[2] : intDiferenca);
	dblDuracao = (args.length > 3 ? args[3] : dblDuracao);

	if(eval('duracaoAtual'+ posicao) >= (tempoDuracao-1)){
		fadeout(_$('imgBanner'+ posicao), 'divTransicao'+ posicao, 12, intDiferenca, dblDuracao);
		clearTimeout(eval('timeout_banner'+ posicao));
		eval('duracaoAtual'+ posicao + ' = 0');
	}
	else{
		eval('duracaoAtual'+ posicao + ' += 1');
		eval("timeout_banner"+ posicao +" = setTimeout(\"verificaTempoTimeOutBanner('"+ tempoDuracao +"', '"+ posicao +"');\", 1000);");
	}
}

function ajax(Link, Metodo, objSpan, QueryString){
	enviaPage(Link, Metodo, 'true', objSpan, QueryString);
}


function getValorElementos(frmForm){
	var parametros = '';
	if(frmForm){
		for(var i = 0; i < frmForm.elements.length; i++){
			var objElemento = frmForm.elements[i];
			var objTipoElemento = objElemento.type;
			if(objTipoElemento == 'text'){
				parametros += '&' + objElemento.name +'='+ _$4(objElemento.id);
			}
			else if(objTipoElemento == 'select-one'){
				parametros += '&' + objElemento.name +'='+ _$5(objElemento.id);
			}
		}
	}
	return parametros;
}
