function abrePagina(pg,w,h){
	var width  = w;
	var height = h;
	var left   = screen.width / 2 - width / 2;
	var top    = screen.height / 2 - height / 2;
	window.open(pg,'','height='+height+',width='+width+',top='+top+',left='+left+',scrollbars=yes,status=yes');
}
function abreJanela(url,w,h){
	var width  = parseInt(w);
	var height = parseInt(h);
	var left   = screen.width / 2 - width / 2;
	var top    = screen.height / 2 - height / 2;

	var x = window.open(url,'Zoom','height='+height+',width='+width+',top='+top+',left='+left+',scrollbars=yes,status=yes')
	x.resizeTo(width+10,height+49);
	x.moveTo(left,top);
	x.focus();
}
function abreAlbumNoticias(id){
	var width  = 772;
	var height = 550;			
	var left   = screen.Width / 2 - width / 2;
	var top    = screen.Height / 2 - height / 2;
	window.open('noticias_album.php?id='+id,'blank','height='+height+',width='+width+',top='+top+',left='+left+',scrollbars=yes,status=yes')
}
function $(element){
  return document.getElementById(element);	
}
//mouse over e on
function mudaImg(id,img){
	document.getElementById(id).src = img;
}

//limita texto
function limitText(limitField, limitCount, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	} else {
		limitCount.value = limitNum - limitField.value.length;
	}
}

function emailValido( value ) {	
return(/^([\w\.\-])+\@(([\w\-])+\.)+([\w ]{2,4})$/.test(value))
}

// Removes leading whitespaces
function LTrim( value ) {	
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
}

// Removes ending whitespaces
function RTrim( value ) {
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
}

// Removes leading and ending whitespaces
function trim( value ) {
	return LTrim(RTrim(value));	
}



function limitText(limitField, limitCount, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	} else {
		limitCount.value = limitNum - limitField.value.length;
	}
}
//mostra ou esconde a tag
function mostraEsconde(id){
	var elemento = document.getElementById(id);
	if(elemento.style.display == 'none'){
		elemento.style.display = 'block';
	} else {
		elemento.style.display = 'none';
	}
	
}

//retorna a extensao do arquivo em maiuscula
	function getExt(file){
		return (file.substring(file.length-3,file.length)).toUpperCase();
	}
	
//========================================
	//Valida o formulario retornando true/false
	function validateArquivoMaling(){

		var form = document.form2;
		var focoElement = null;
		var array_erro = new Array();
		//Reinica as cores das bordas
		form.arquivo.style.borderColor      = '';
		//Verificação dos campos obrigatorios
		//Nome
		if(form.arquivo.value == ''){
			array_erro.push('Selecione um arquivo.');
			if(focoElement == null)
				focoElement = form.arquivo;
		}
        
		//Arquivo
		if(!form.separacao[0].checked && !form.separacao[1].checked){
			array_erro.push('Selecione o modo de separação dos emails no arquivo.');
		}

		//Arquivo
		if(form.arquivo.value != ''){
			var ext = getExt(form.arquivo.value);
			if(ext != 'CSV' && ext != 'TXT'){
				array_erro.push('Formato de arquivo inválido para inportação (Somente csv e txt)');
				form.arquivo.style.borderColor = 'red';
				if(focoElement == null)
					focoElement = form.arquivo;
			}			
		}		
			
																	
		var numErros = array_erro.length;
		if(numErros > 0){
			var str = 'Foram encontrados os seguintes erros:\n';
			for(i = 0; i < numErros; i++){
				str += '\n - ' + array_erro[i];
			}
			alert(str);
			focoElement.focus();
			return false;
		} else {

				form.action ='usuarios_newsletter_usuarios_cadastro_lote_arquivo.php';
			return true;
		}		
	} // Fim validate()
	
//========================================	

function excluirEmailMarketing(id){
	if(confirm('Excluir este Email Marketing ?'))
		document.location.href = 'emarketing_excluir.php?id=' + id;
}

function visualizarEmailMarketing(id){
	var width  = 618;
	var height = 500;
	var left   = screen.Width / 2 - width / 2;
	var top    = screen.Height / 2 - height / 2;
	window.open('emarketing_visualizar.php?id='+id,'','height='+height+',width='+width+',top='+top+',left='+left+',scrollbars=yes,status=yes');
}

function excluirCampanhas(id){
	if(confirm('Excluir esta Campanha ?'))
		document.location.href = 'campanhas_excluir.php?id=' + id;
}


function getIndexByValue(selectObj,val){
	var n = -1;
	for(i=0; i<selectObj.options.length; i++)
		if (selectObj.options[i].value == val)
			n = i;
		
	return n;
}

function validaNoticia(){
		var form = document.form1;
		var focoElement = null;
		var array_erro = new Array();
		
		//Reinica as cores das bordas
		form.titulo.style.borderColor  = '';
		form.chamada.style.borderColor = '';
		form.texto.style.borderColor   = '';
		form.imagem1.style.borderColor = '';
		form.desc1.style.borderColor   = '';
		//Verificação dos campos obrigatorios
		//titulo
		if(form.titulo.value == ''){
			array_erro.push('Título não preenchido');
//			form.titulo.style.borderColor = 'red';
			if(focoElement == null)
				focoElement = form.titulo;
		}
		//Chamada
		if(form.chamada.value == ''){
			array_erro.push('Chamada não preenchido');
//			form.chamada.style.borderColor = 'red';
			if(focoElement == null)
				focoElement = form.chamada;
		}		
		//texto
		if(form.texto.value == ''){
			array_erro.push('Texto não preenchido');
//			form.texto.style.borderColor = 'red';
			if(focoElement == null)
				focoElement = form.texto;
		}			
		//imagem1
		if(form.imagem1.value != '' && form.desc1.value == ''){
			array_erro.push('Descrição 1 não preenchida');
//			form.desc1.style.borderColor = 'red';
			if(focoElement == null)
				focoElement = form.desc1;
		}
																	
		var numErros = array_erro.length;
		if(numErros > 0){
			var str = 'Foram encontrados os seguintes erros:\n';
			for(i = 0; i < numErros; i++){
				str += '\n - ' + array_erro[i];
			}
			alert(str);
			focoElement.focus();
			return false;
		} else {
			return true;
		}		
	} // Fim validate()

function filtraGrupos (doc){
	if (doc.form1.categoria.selectedIndex > 0){
		temp = '^'+doc.form1.categoria.options[doc.form1.categoria.selectedIndex].value+'FIM'; 
		myfilter.set(temp);
		showHide('grupoTR','show');
	}
	else{
		doc.form1.grupo.selectedIndex = 0;
		showHide('grupoTR','hide');
	}	
}
function showHide(id, param){
	var elemento = document.getElementById(id);
	if(param == 'show'){
		elemento.style.display = 'inline';
	} else {
		elemento.style.display = 'none';
	}
	
}


function SelecionaGrupo(form, submitForm){
if (form.grupo.options[form.grupo.selectedIndex].value != ''){
	var temp = form.grupo.options[form.grupo.selectedIndex].value.split("FIM");
//	if(confirm('Selecionar o grupo ' + form.grupo.options[form.grupo.selectedIndex].text + '?')){
	form.idgrupo.value = temp[1];
	form.nomegrupo.value = form.categoria.options[form.categoria.selectedIndex].text + ' -> '+form.grupo.options[form.grupo.selectedIndex].text;
	if (submitForm)
			form.submit();					
//	}
}
else
	alert ('Selecione o Grupo.');
}



//para ajax
function setDeleta(autent) {
   if (autent == 'sim'){
	   alert('Foto excluida!!');
   }else{
	   alert('A foto não pode ser excluida!!');
   }
}

function getDeleta(foto) {  //função que recebe os valores
		if(confirm('Excluir esta imagem? ')){
			x_deletaFoto(foto, setDeleta);
			document.getElementById('desc1').value = "";
		}
}
//----------
function abreImagem(file,w,h){
	var width  = parseInt(w);
	var height = parseInt(h);
	var left   = screen.width / 2 - width / 2;
	var top    = screen.height / 2 - height / 2;

	var x = window.open('zoom.php?file='+file+'&width='+w+'&height='+h,'Zoom','height='+height+',width='+width+',top='+top+',left='+left+',scrollbars=no,status=yes')
	x.resizeTo(width+10,height+49);
	x.moveTo(left,top);
	x.focus();
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}



function excluirGrupoUsuario(id,nome){
	if((id == 0) || (id == 1) || (id == 2)){
		alert('Não é possível excluir o grupo ' + nome);
	} else {
		if(confirm('Excluir o grupo: ' + nome + '?'))
			document.location.href = 'usuarios_newsletter_grupos_excluir.php?id=' + id;	
	}
}

function copyStringTo(item,str){
	var element = document.getElementById(item);
	element.value += str;
	element.focus();
}

function excluirGrupoRepresentantes(id,nome){
	if((id == 0)){
		alert('Não é possível excluir o grupo ' + nome);
	} else {
		if(confirm('Excluir o grupo: ' + nome + '?'))
			document.location.href = 'representantes_grupos_excluir.php?id=' + id;	
	}
}

function excluirAlbum(id,nome){
	if(confirm('Excluir o álbum: ' + nome + '?\n\nAtenção: Todas as fotos também serão excluídas.'))
		document.location.href = 'album_excluir.php?id=' + id;
}

function excluirNewsletter(id){
	if(confirm('Excluir a newsletter?'))
		document.location.href = 'newsletter_excluir.php?id=' + id;
}

function visualizarNewsletter(id){
	var width  = 700;
	var height = 500;
	var left   = screen.Width / 2 - width / 2;
	var top    = screen.Height / 2 - height / 2;
	window.open('newsletter_visualizar.php?id='+id,'','height='+height+',width='+width+',top='+top+',left='+left+',scrollbars=yes,status=yes');
}

function selectCheckBox(theBoxes,value){
	var qtd = theBoxes.length;	
	if(qtd){
		for(i = 0 ; i < qtd; i++){
			theBoxes[i].checked = value;
		}	
	} else {
		theBoxes.checked = value;
	}
}

function selectOptions(comboID,value){
	var combo = document.getElementById(comboID);
	var numOptions = combo.options.length;
	for(var i = 0; i < numOptions; i++){
		combo.options[i].selected = value;		
	} 

}

function selectCheckBox2(name,value){
	var element = document.getElementsByName(name);
	var qtd = element.length;	
	if(qtd){
		for(i = 0 ; i < qtd; i++){
			element[i].checked = value;
		}	
	} else {
		element.checked = value;
	}
}

function checkTheBox(theBox){
	theBox.checked = !theBox.checked;
}

function confirmar(texto){
	if(confirm(texto))
		return true
	else 
		return false
}

function confirmarLink(texto,url){
	if(confirm(texto))
		document.location.href=url;
}

function lembreteSenha(){
	window.open('usuarios_senha.php','','width=320,height=100');
}

function grabFocus(item){
	item.focus();
}

function janelaSelecaoGrupo(submitForm){
	var width  = 300;
	var height = 170;
	var left   = screen.Width / 2 - width / 2;
	var top    = screen.Height / 2 - height / 2;
	window.open('produto_cadastro_selecionar_grupo.php?submitForm='+submitForm,'PLATTSELGRUPO','height='+height+',width='+width+',top='+top+',left='+left+',scrollbars=no,status=yes');
}

function selecionarGrupo(id,nome,submitForm){

	if(confirm('Selecionar o grupo ' + nome + '?')){
		self.opener.form1.idgrupo.value = id;
		self.opener.form1.nomegrupo.value = nome;
		if(submitForm == 'true')	
			self.opener.form1.submit();
		self.close();
					
	}

}

function showHideItem(id){
	var elemento = document.getElementById(id);
	if(elemento.style.display == 'none'){
		elemento.style.display = 'inline';
	} else {
		elemento.style.display = 'none';
	}
	
}


	function moveItem(qtd){
		var index = document.form1.produtos.selectedIndex;
		if(index != -1){
			var total = document.form1.produtos.length;
			var target = index + qtd;
			if(target > -1 && target < total){
				var aux = new Option(document.form1.produtos.options[index].text,document.form1.produtos.options[index].value);
				document.form1.produtos.options[index].text = document.form1.produtos.options[target].text;
				document.form1.produtos.options[index].value = document.form1.produtos.options[target].value;
				document.form1.produtos.options[target].text = aux.text;		
				document.form1.produtos.options[target].value = aux.value;
				document.form1.produtos.options[target].selected = true;
			} else {
				alert("Ação inválida.");
			}
		} else {
			alert("Nenhum item selecionado.");			
		}
	}
	
	function salvarOrdenacao(){
		if(confirmar('Salvar alterações?')){
			var total = document.getElementById('produtos').length;
			document.getElementById('listaID').value = implode(';;',document.getElementById('produtos').options);
			document.getElementById('form1').submit();	
		}
	}
	
	/**
	 * implode: pega todos os elementos do array pieces e junta em uma string utilizado glue como separador
	 * @param glue: String separadora dos elementos
	 * @param pieces: array com os elementos a serem concatenados	
	 */
function implode(glue,pieces){
		var str = "";
		var numPieces = pieces.length;
		for(var i = 0; i < (numPieces-1); i++){
			str += pieces[i].value + glue;
		}
		str += pieces[i].value;
		return str;
}		

function banner(id,tipo,w,h){
	var width  = w;
	var height = h;
	var left   = screen.Width / 2 - width / 2;
	//var top    = screen.Height / 2 - height / 2;
	var top = 120;
	window.open('banner_visualizar.php?id='+id+'&tipo='+tipo+'&w='+w+'&h='+h,'','height='+height+',width='+width+',top='+top+',left='+left+',scrollbars=no,status=no');
}

function promocao(id,tipo,w,h){
	var width  = w;
	var height = h;
	var left   = screen.Width / 2 - width / 2;
	//var top    = screen.Height / 2 - height / 2;
	var top = 120;
	window.open('promocao_visualizar.php?id='+id+'&tipo='+tipo+'&w='+w+'&h='+h,'','height='+height+',width='+width+',top='+top+',left='+left+',scrollbars=no,status=no');
}


function enviar(pagina,valor){

 document.form1.opcao.value = valor; 	
 document.form1.action = pagina;
 document.form1.submit();

}

function irpara(pagina){
 
 //document.form1.method="get"; 
 document.form1.action = pagina;
 document.form1.submit();
 }
 
 function verificaAcesso(acesso){      
	var acesso = acesso; 
	if(acesso == 1){
		document.form1.method = "post";
		document.form1.submit();
		
	}
	else{
		alert("Usuário sem permissão.");
		document.form1.method = "get"; 
		document.form1.submit();
	}
}
                                   
//formatacao de numeros de moedas
function Limpar(valor, validos) { 
// retira caracteres invalidos da string 
var result = ""; 
var aux; 
for (var i=0; i < valor.length; i++) { 
aux = validos.indexOf(valor.substring(i, i+1)); 
if (aux>=0) { 
result += aux; 
} 
} 
return result; 
} 

//Formata número tipo moeda usando o evento onKeyDown 
//chamada: texto1: <input type="text" name="texto" size="20" onKeydown="Formata(this,20,event,2)"> 

function Formata(campo,tammax,teclapres,decimal) { 
var tecla = teclapres.keyCode; 
vr = Limpar(campo.value,"0123456789");
tam = vr.length; 
dec=decimal 

if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; } 

if (tecla == 8 ) 
{ tam = tam - 1 ; } 

if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ) 
{ 

if ( tam <= dec ) 
{ campo.value = vr ; } 

if ( (tam > dec) && (tam <= 5) ){ 
campo.value = vr.substr( 0, tam - 2 ) + "." + vr.substr( tam - dec, tam ) ; } 
if ( (tam >= 6) && (tam <= 8) ){ 
campo.value = vr.substr( 0, tam - 5 ) + vr.substr( tam - 5, 3 ) + "." + vr.substr( tam - dec, tam ) ; 
} 
if ( (tam >= 9) && (tam <= 11) ){ 
campo.value = vr.substr( 0, tam - 8 ) + vr.substr( tam - 8, 3 ) + vr.substr( tam - 5, 3 ) + "." + vr.substr( tam - dec, tam ) ; } 
if ( (tam >= 12) && (tam <= 14) ){ 
campo.value = vr.substr( 0, tam - 11 ) + vr.substr( tam - 11, 3 ) + vr.substr( tam - 8, 3 ) + vr.substr( tam - 5, 3 ) + "." + vr.substr( tam - dec, tam ) ; } 
if ( (tam >= 15) && (tam <= 17) ){ 
campo.value = vr.substr( 0, tam - 14 ) + vr.substr( tam - 14, 3 ) + vr.substr( tam - 11, 3 ) + vr.substr( tam - 8, 3 ) + vr.substr( tam - 5, 3 ) + "." + vr.substr( tam - 2, tam ) ;} 
} 

} 