/*
================================================================================================
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;
	for(intCont = 0; intCont < frmFormulario.elements.length; intCont++){
		objCampo = frmFormulario.elements[intCont];
		var strValor = buscarCampoValor(objCampo.id);
		
		if(strValor != null && strValor != undefined){
			arrValor = strValor.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] == '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] == 'DATA'){
					if(!objCampo.value.trim().isData()){
						strMsg += '- Campo ' + arrValor[1] + ' não é uma data válida\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:		13/06/2008
DESCRICAO:	FUNCAO PARA VERIFICAR OS ATRIBUTOS ATRAS DO CAMPO "VALOR"
			PADRONIZAÇÃO DE NAVEGADOR
EXEMPLO:	buscarCampoValor(idCampo ou NomeCampo)
================================================================================================
*/
function buscarCampoValor(objCampo){
	if(objCampo != null && objCampo != undefined && objCampo != ''){
		if(document.all){
			objCampo = document.all[objCampo];
		}
		else if (document.getElementById){
			objCampo = document.getElementById(objCampo);
		}
		if(objCampo != null && objCampo != undefined && objCampo != ''){
			var objAtributos = objCampo.attributes;
			if(objAtributos){
				if(objAtributos.length){
					for(var i=0; i < objAtributos.length;i++){
						if(objAtributos[i].specified){
							if(objAtributos[i].nodeName == 'valor'){
								return objAtributos[i].nodeValue;
							}
						}
					}
				}
			}
		}
	}
	return null;
}


/*
================================================================================================
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 UMA DATA NO FORMATO DD/MM/AAAA.
EXEMPLO:	NO FORMULARIO -> variavelString.isData()
================================================================================================
*/
String.prototype.isData = function() {
	var dateStr = this;
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
	var matchArray = dateStr.match(datePat); // is the format ok?

	if (matchArray == null) {
		return false;
	}

	// Separe as datas dentro das variáveis
	day = matchArray[1];
	month = matchArray[3];
	year = matchArray[5];

	if (month < 1 || month > 12) { // Checagem dentro do range
		return false;
	}

	if (day < 1 || day > 31) {
		return false;
	}

	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		return false;
	}

	if (month == 2) { // Checagem do mês de fevereiro (29ª dia)
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day > 29 || (day==29 && !isleap)) {
			return false;
		}
	}
	return true;
}

// Verifica se a data apresentada ou no uma data válida
String.prototype.isDataV2 = function() {
    //IsDate(29, 2, 2005)
    //IsDate(29, 2, 2004)
	var dateStr = this;
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
	var matchArray = dateStr.match(datePat);
    var date = new Date();
    var blnRet = false;
    var blnDay;
    var blnMonth;
    var blnYear;

	if (matchArray == null) {
		return false;
	}

	// Separe as datas dentro das variáveis
	day = parseInt(matchArray[1]);
	month = parseInt(matchArray[3]);
	year = parseInt(matchArray[5]);
    date.setFullYear(year, month-1, day);

    blnDay   = (date.getDate()  == day);
    blnMonth = (date.getMonth() == month-1);
    blnYear  = (date.getYear()  == year);

    if (blnDay && blnMonth && blnYear)
        blnRet = true;

    return blnRet;
}


/*
================================================================================================
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();');
}

function goToPageOption(objPaginacao, intPagina, intLimite, strComplementoURL){
	var strURL = '';

	if(objPaginacao != undefined){
		intPagina = objPaginacao.options[objPaginacao.selectedIndex].value;
		if(intPagina > intLimite || intPagina < 1 || isNaN(intPagina)){
			alert('Por favor, informe uma página dentro do intervalo de 1 à ' + intLimite);
			objPaginacao.focus();
			return false;
		}
		strURL = '?pagina=' + intPagina + (strComplementoURL != '' ? '&' + strComplementoURL : '');
		self.location.replace(strURL);
		return true;
	}
	return false;
}
	
function goToPageOptionPost(objPaginacao, intPagina, intLimite, strComplementoURL, frmFormBusca){
	var strURL = '';

	if(objPaginacao != undefined){
		intPagina = objPaginacao.options[objPaginacao.selectedIndex].value;
		if(intPagina > intLimite || intPagina < 1 || isNaN(intPagina)){
			alert('Por favor, informe uma página dentro do intervalo de 1 à ' + intLimite);
			objPaginacao.focus();
			return false;
		}
		else{
			var frmBusca = document.getElementById(frmFormBusca);
			if(frmBusca){
				frmBusca.pagina.value = intPagina;
				frmBusca.submit();
				return true;
			}
		}
	}
	return false;
}

function debugForm(frmFormulario){
	for(var i = 0; i < frmFormulario.elements.length; i++){
		var objElementoAtual = frmFormulario.elements[i];
		var strDado = (objElementoAtual.id ? 'ID: ' + objElementoAtual.id + ' / ' + (objElementoAtual.name ? 'NAME: ' + objElementoAtual.name : '') : '') + ' = ' + (objElementoAtual.value ? 'VALUE: ' + objElementoAtual.value : '');
		alert(strDado + '\n');
	}
}

function mostrarEsconderCampo(objCampoMostrar, objCampoEsconder){
	var objCampoEsconder = _$(objCampoEsconder);
	var objCampoMostrar = _$(objCampoMostrar);
	
	if(objCampoMostrar.id != objCampoEsconder.id){
		if(objCampoEsconder){
			objCampoEsconder.style.display = 'none';
		}
		if(objCampoMostrar){
			objCampoMostrar.style.display = '';
		}
	}
	else{
		objCampoMostrar.style.display = (objCampoMostrar.style.display == '' ? 'none' : '');
	}
}
