/*
================================================================================================
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'){
				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] == '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 validaEnquete(frmFormulario){
	strMsg = '';
	objCampoFocus = undefined;
	var blnRetorno = verificaCampo(frmFormulario);

	if(strMsg != ''){
		alert(strMsg);
		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 adicionar(Tipo){
	document.location.href = Tipo + '_Cadastro.aspx';
}

function atualizar(URL, IDRegistro){
	document.location.href = URL + '_Atualizar.asp?ID=' + IDRegistro;
}

function visualizar(URL, IDRegistro){
	window.open('../' + URL + '/' + URL + '_Visualizar.aspx?ID=' + IDRegistro, 'MailMktSolution_Modelo_'+ IDRegistro, 'scrollbars=1, resizable=0', 'top=0, left=0');
}

function atualizarIFrame(URL, IDRegistro, IFrame){
	var iFrame = eval("window.document." + IFrame + ".document");
	if(iFrame != undefined){
		iFrame.location.href = URL + '_Atualizar.aspx?IDAcao=2&ID=' + IDRegistro;
	}
}

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 excluirIFrame(){
	var args = excluirIFrame.arguments;
	var strUrlAtual = document.location.href.replace('#', '');
	var chkListaItens = document.forms[0].chkItem;
	var idcFrame = window.ifrConteudo.document;
	if(idcFrame != undefined && chkListaItens != undefined){
		var idRegistros = '';
		if(chkListaItens.length > 1){
			for(var i = 0; i < chkListaItens.length; i++){
				if(chkListaItens[i].checked){
					idRegistros += chkListaItens[i].value + ',';
				}
			}
			if(idRegistros != '')
				idRegistros = idRegistros.substring(0, idRegistros.length-1);
		}
		else{
			idRegistros = chkListaItens.value;
		}	
		idcFrame.location.href = strUrlAtual + '?IDAcao=3&ID=' + idRegistros + (args[0] != undefined ? args[0] : '');
	}
	else{
		alert('Não existe nenhum item para ser excluído.');
	}
}

function excluirEmailsIFrame(){
	var args = excluirIFrame.arguments;
	var strUrlAtual = document.location.href.replace('#', '');
	var chkListaItens = document.forms[0].chkItem;
	var idcFrame = window.ifrConteudo.document;
	var optCategoria = document.forms[0].ddlCategorias;
	var intIDCategoria = optCategoria.options[optCategoria.selectedIndex].value;
	var blnContinuar = false;
	var strPergunta = '';
	
	if(intIDCategoria == '-1')
		strPergunta = 'Os emails excluídos serão atualizados em \"Todas as Categorias em que estejem cadastrados\" para o status de descadastrados e inativos.\nEles não serão excluídos da base de dados.\n\nDeseja continuar ?';
	else
		strPergunta = 'Os emails excluídos serão atualizados em para o status de descadastrados e inativos.\nEles não serão excluídos da base de dados.\n\nDeseja continuar ?';

	blnContinuar = confirm(strPergunta);
	if(blnContinuar){
		if(idcFrame != undefined && chkListaItens != undefined){
			var idRegistros = '', idCategorias = '';
			if(chkListaItens.length > 1){
				for(var i = 0; i < chkListaItens.length; i++){
					if(chkListaItens[i].checked){
						idRegistros += chkListaItens[i].value + ',';
						if(chkListaItens[i].IDCategoria != null && chkListaItens[i].IDCategoria != undefined)
							idCategorias += chkListaItens[i].IDCategoria + ',';
					}
				}
				if(idRegistros != '')
					idRegistros = idRegistros.substring(0, idRegistros.length-1);
				if(idCategorias != ''){
					if(intIDCategoria == '-1')
						idCategorias = intIDCategoria;
					else
						idCategorias = idCategorias.substring(0, idCategorias.length-1);
				}
			}
			else{
				idRegistros = chkListaItens.value;
				if(chkListaItens.IDCategoria != null && chkListaItens.IDCategoria != undefined)
					idCategorias = chkListaItens.IDCategoria;
			}
				
			idcFrame.location.href = strUrlAtual + '?IDAcao=3&ID=' + idRegistros + "&IDCategoria=" + idCategorias;
		}
		else{
			alert('Não existe nenhum item para ser excluído.');
		}
	}
	return blnContinuar;
}

function codigoCategoriasItens(){
	var args = excluirIFrame.arguments;
	var hddChkListaItens = document.forms[0].hddChkItemCategoria;
	var chkListaItens = document.forms[0].chkItem;
	var optCategoria = document.forms[0].ddlCategorias;
	var intIDCategoria = optCategoria.options[optCategoria.selectedIndex].value;
	var idCategorias = '';
	if(chkListaItens.length > 1){
		for(var i = 0; i < chkListaItens.length; i++){
			if(chkListaItens[i].checked){
				if(chkListaItens[i].IDCategoria != null && chkListaItens[i].IDCategoria != undefined)
					idCategorias += chkListaItens[i].IDCategoria + ',';
			}
		}
		if(idCategorias != ''){
			if(intIDCategoria == '-1')
				idCategorias = intIDCategoria;
			else
				idCategorias = idCategorias.substring(0, idCategorias.length-1);
		}
	}
	hddChkListaItens.value = idCategorias;
}

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 buscarProdutoEmpresa(frmBusca){
	var intLimiteMinimo = 3;
	var blnProdutoOk = false, blnEmpresaOK = false;
	frmBusca = document.getElementById(frmBusca);
	if(frmBusca){
		var strURLBusca = '';
		var txtBuscaProduto = document.getElementById('txtBuscaProduto');
		var txtBuscaEmpresa = document.getElementById('txtBuscaEmpresa');

		if(txtBuscaProduto && txtBuscaEmpresa){
			if(isTamanhoValido(txtBuscaProduto.value, 3, -1)){
				strURLBusca = 'produtoBuscaPalavra.asp';
				txtBuscaEmpresa.value = '';
				blnProdutoOk = true;
			}
			if(isTamanhoValido(txtBuscaEmpresa.value, 3, -1)){
				strURLBusca = 'empresaBuscaPalavra.asp';
				blnEmpresaOK = true;
			}
		}
		if(blnProdutoOk || blnEmpresaOK){
			frmBusca.action = strURLBusca;
			frmBusca.submit();
		}
		else{
			var strMsg = '';
			if(!blnProdutoOk){
				strMsg += '• A busca por produtos deve ter no mínimo '+ intLimiteMinimo + ' caracteres.\n';
			}
			if(!blnEmpresaOK){
				strMsg += '• A busca por empresas deve ter no mínimo '+ intLimiteMinimo + ' caracteres.\n';
			}
			alert('Por favor preencha corretamente os campos:\n\n' + strMsg);
		}
	}
}

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;
	}
}