function validaForm(f) {
	avisos = "";
	for(i=0;i<f.length;i++) {
		id = f.elements[i].id;
		id = id.substr(0,4);
		name = f.elements[i].name;
		if(id == "vTxt") fTexto(f.elements[i]);
		if(id == "vEm0") fEmail(f.elements[i],false);
		if(id == "vEm1") fEmail(f.elements[i],true);
		if(name == "tx_senha") fSenha(f);
		if(id == "vCpf") fCpf(f.elements[i]);
		/*
		if(id == "vfSelect") fSelect(f.elements[i]);
		if(id == "vfEmail") fEmail(f.elements[i]);
		if(id == "vfNumero") fNumero(f.elements[i]);
		if(id == "vfMoeda") fMoeda(f.elements[i]);
		if(id == "vfData") fData(f.elements[i],1);
		if(id == "vfDataN") fData(f.elements[i],0);
		if(id == "vfUnico") fUnico(f.elements[i],i);
		if(id == "vfUnicoEmail") fUnicoEmail(f.elements[i],i);
		*/
	}
	if(avisos!="") {
		alert("Verifique o preenchimento do formulário\n\n"+avisos);
	} else {
		f.submit();
	}
}
function ir(url) {
	window.location.href=url;	
}
function voltar() {
	window.history.back();
}
// Trata campos texto obrigatórios ----/
function fTexto(campo) {
	if(campo.type=="select-one") {
		if(campo.selectedIndex==0) {
			cp = campo.title;
			avisos = avisos + " - O campo "+cp+" é obrigatório!\n";
		}
	} else {
		if(campo.value.length < 3) {
			if(campo.alt)
				cp = campo.alt;
			else
				cp = campo.title;
			avisos = avisos + " - O campo "+cp+" é obrigatório!\n";
		}
	}
}
// Trata campo senha
function fSenha(form) {
	if(form.tx_senha.value!="" && form.ex_senha.value!="" && form.tx_senha.value!=form.ex_senha.value) {
		avisos = avisos + " - Confirme a senha corretamente!\n";
	}
}
//Trata campo CPF
function fCpf(campo) {
erro = false;
cpf = campo.value;
if (cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999")
erro = true;
soma = 0;
for (i=0; i < 9; i ++)
soma += parseInt(cpf.charAt(i)) * (10 - i);
resto = 11 - (soma % 11);
if (resto == 10 || resto == 11)
resto = 0;
if (resto != parseInt(cpf.charAt(9))) erro = true;
soma = 0;
for (i = 0; i < 10; i ++)
soma += parseInt(cpf.charAt(i)) * (11 - i);
resto = 11 - (soma % 11);
if (resto == 10 || resto == 11)
resto = 0;
if (resto != parseInt(cpf.charAt(10))) erro = true;
if(erro)
avisos = avisos + " - Preencha o campo "+campo.alt+" com um CPF válido!\n";
}
// Trata o e-mail válido ----/
function fEmail(campo,obrigatorio) {
	if(obrigatorio || campo.value!="") {
		rexp = new RegExp("/^[\w!#$%&'*+\/=?^`{|}~-]+(\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/");
		if(!rexp.test(campo.value)) {
			avisos = avisos + " - Preencha o campo "+campo.alt+" com um e-mail válido!\n";
		}
	}
}
function rascunho() {
	window.document.fDados.in_ativo.value=0;
	if(window.document.fDados.tx_titulo.value=="")
		validaForm(window.document.fDados);
	else
		window.document.fDados.submit();
}
function publicar() {
	window.document.fDados.in_ativo.value=1;
	if(window.document.fDados.tx_titulo.value=="")
		validaForm(window.document.fDados);
	else
		window.document.fDados.submit();
}
function abre(url) {
	window.open(url,'pop','width=1,height=1');
	void(0);
}
function enviaIndica() {
	window.open('_incs/indicar.php','popIndica','width=500,height=242');
	void(0)
}

function isValidEmail(email, required) {
    if (required==undefined) {   // if not specified, assume it's required
        required=true;
    }
    if (email==null) {
        if (required) {
            return false;
        }
        return true;
    }
    if (email.length==0) {  
        if (required) {
            return false;
        }
        return true;
    }
    if (! allValidChars(email)) {  // check to make sure all characters are valid
        return false;
    }
    if (email.indexOf("@") < 1) { //  must contain @, and it must not be the first character
        return false;
    } else if (email.lastIndexOf(".") <= email.indexOf("@")) {  // last dot must be after the @
        return false;
    } else if (email.indexOf("@") == email.length) {  // @ must not be the last character
        return false;
    } else if (email.indexOf("..") >=0) { // two periods in a row is not valid
	return false;
    } else if (email.indexOf(".") == email.length) {  // . must not be the last character
	return false;
    }
    return true;
}

function allValidChars(email) {
  var parsed = true;
  var validchars = "abcdefghijklmnopqrstuvwxyz0123456789@.-_";
  for (var i=0; i < email.length; i++) {
    var letter = email.charAt(i).toLowerCase();
    if (validchars.indexOf(letter) != -1)
      continue;
    parsed = false;
    break;
  }
  return parsed;
}

function soNumeros(e) {
	if(window.event) { // IE
		tecla = e.keyCode
	} else if(e.which) { // Netscape/Firefox/Opera
		tecla = e.which
	}
	if((tecla < 48 && tecla != 8)||(tecla > 57)) {
		 	return false;
	}	
}

function soMoeda(objeto, e) {
	if(window.event) { // IE
		tecla = e.keyCode
	} else if(e.which) { // Netscape/Firefox/Opera
		tecla = e.which
	}
	if(tecla == 44) {
		if(objeto.value.indexOf(",")!=-1) {
			return false;
		}
	}
	else {
		if((tecla < 48 && tecla != 8)||(tecla > 57)) {
		 	return false;
		}
	}	
}


var hImagem = function(t) {window.document.getElementById("resp_imagens").innerHTML = t.responseText;}
var eImagem = function(t) {return false;}
function excluiImg(c,i) {
	var url	= "../../ajax/admImgExclui.php";
	if(confirm("A imagem será excluída!\nVocê tem certeza?"))
		new Ajax.Request(url, {method:'get', parameters:'c='+c+'&i='+i, onSuccess:hImagem, onFailure:eImagem});
}
var hprodutoC = function(t) {window.document.getElementById("produtoC").innerHTML = t.responseText;}
var eprodutoC = function(t) {return false;}
function dropProdutoC(c,f,i) {
	var url	= "../../ajax/admProdutos.php";
	new Ajax.Request(url, {method:'get', parameters:'c='+c+'&campo='+f+'&i='+i, onSuccess:hprodutoC, onFailure:eprodutoC});
}
var hprodutoR = function(t) {window.document.getElementById("produtoR").innerHTML = t.responseText;}
var eprodutoR = function(t) {return false;}
function dropProdutoR(c,f,i) {
	var url	= "../../ajax/admProdutos.php";
	new Ajax.Request(url, {method:'get', parameters:'c='+c+'&campo='+f+'&i='+i, onSuccess:hprodutoR, onFailure:eprodutoR});
}
function incCasado() {
	if(window.document.fDados.ex_produtoc.value=="") {
		alert("Selecione um produto");
	} else {
		var arr = new Array();
		arr[0] = window.document.fDados.ex_produtoc[window.document.fDados.ex_produtoc.selectedIndex].value;
		arr[1] = window.document.fDados.ex_produtoc[window.document.fDados.ex_produtoc.selectedIndex].text;
		inc = true;
		for(i=0;i<arrCasadas.length;i++) {
			if(arr[0] == arrCasadas[i][0]) {
				alert("Este produto já está relacionado");			
				inc = false;
			}
		}		
		if(inc) {
			arrCasadas.push(arr);
			montaCasada();			
		}
		window.document.fDados.ex_categoriac.selectedIndex=0;
		while(window.document.fDados.ex_produtoc.length>0)window.document.fDados.ex_produtoc[0]=null;
		window.document.fDados.ex_produtoc[0] = new Option("---escolha uma categoria primeiro","---escolha uma categoria primeiro");		
	}
}
function montaCasada() {
	saida = "";
	if(arrCasadas.length>0) {
		saida = "<table id=\"tabRel\"><tr><th width=\"30\">&nbsp;</th><th width=\"350\">Produto</th><th width=\"30\">&nbsp;</th></tr>";
		for(i=0;i<arrCasadas.length;i++) {
			saida += "<tr><td><img src=\"../../lib/imgSite.php?c=../media/produtos/img01"+arrCasadas[i][0]+".jpg&l=45\" /><input type=\"hidden\" name=\"ex_prodC[]\" value=\""+arrCasadas[i][0]+"\" /></td><td>"+arrCasadas[i][1]+"</td><td align=\"center\"><a href=\"javascript:excCasada("+arrCasadas[i][0]+");\"><img src=\"../../media/icons/x.gif\" /></a></td></tr>"; 
		}
		saida += "</table>";
	} else {
		saida = "<center>Nenhum produto cadastrado para venda casada</center>";
	}
	window.document.getElementById("lista_casada").innerHTML = saida;
}
function excCasada(id) {
	if(confirm("Tem certeza que deseja tirar o produto do relacionamento?")) {
		cont = 0;
		var arrNova = new Array();
		for(i=0;i<arrCasadas.length;i++) {
			if(arrCasadas[i][0]==id) {
			} else {
				arrNova[cont] = arrCasadas[i];
				cont++;
			}
		}
		saida = "";
		arrCasadas = arrNova;
		montaCasada();
	}
}
function incRelacionado() {
	if(window.document.fDados.ex_produtor.value=="") {
		alert("Selecione um produto");
	} else {
		var arr = new Array();
		arr[0] = window.document.fDados.ex_produtor[window.document.fDados.ex_produtor.selectedIndex].value;
		arr[1] = window.document.fDados.ex_produtor[window.document.fDados.ex_produtor.selectedIndex].text;
		inc = true;
		for(i=0;i<arrRelacionados.length;i++) {
			if(arr[0] == arrRelacionados[i][0]) {
				alert("Este produto já está relacionado");			
				inc = false;
			}
		}		
		if(inc) {
			arrRelacionados.push(arr);
			montaRelacionado();			
		}
		window.document.fDados.ex_categoriar.selectedIndex=0;
		while(window.document.fDados.ex_produtor.length>0)window.document.fDados.ex_produtor[0]=null;
		window.document.fDados.ex_produtor[0] = new Option("---escolha uma categoria primeiro","---escolha uma categoria primeiro");		
	}
}
function montaRelacionado() {
	saida = "";
	if(arrRelacionados.length>0) {
		saida = "<table id=\"tabRel\"><tr><th width=\"30\">&nbsp;</th><th width=\"350\">Produto</th><th width=\"30\">&nbsp;</th></tr>";
		for(i=0;i<arrRelacionados.length;i++) {
			saida += "<tr><td><img src=\"../../lib/imgSite.php?c=../media/produtos/img01"+arrRelacionados[i][0]+".jpg&l=45\" /><input type=\"hidden\" name=\"ex_prodR[]\" value=\""+arrRelacionados[i][0]+"\" /></td><td>"+arrRelacionados[i][1]+"</td><td align=\"center\"><a href=\"javascript:excRelacionado("+arrRelacionados[i][0]+");\"><img src=\"../../media/icons/x.gif\" /></a></td></tr>"; 
		}
		saida += "</table>";
	} else {
		saida = "<center>Nenhum produto cadastrado para venda casada</center>";
	}
	window.document.getElementById("lista_relacionada").innerHTML = saida;
}
function excRelacionado(id) {
	if(confirm("Tem certeza que deseja tirar o produto do relacionamento?")) {
		cont = 0;
		var arrNova = new Array();
		for(i=0;i<arrRelacionados.length;i++) {
			if(arrRelacionados[i][0]==id) {
			} else {
				arrNova[cont] = arrRelacionados[i];
				cont++;
			}
		}
		saida = "";
		arrRelacionados = arrNova;
		montaRelacionado();
	}
}
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
function admmenu(id) {
	if(window.document.getElementById(id).className=="adm_menu_off") {
		window.document.getElementById(id).className="adm_menu_on";
		window.document.getElementById("img"+id).src="../../media/icons/minus.gif";
	} else {
		window.document.getElementById(id).className="adm_menu_off";
		window.document.getElementById("img"+id).src="../../media/icons/plus.gif";
	}
}
function mnDrop(id,st) {
	if(st==1) // Over
		window.document.getElementById(id).style.visibility = "visible";

	if(st==3) { // Out
		tmpMN = window.setTimeout("window.document.getElementById('"+id+"').style.visibility = 'hidden';",1000);
	}
	if(st==4) { // Move
		window.document.getElementById(id).style.visibility = "visible";
		if(tmpMN) window.clearTimeout(tmpMN);
	}
	
	if(st==2) {
		if(tmpMN)
		window.clearTimeout(tmpMN);
	}
	if(st==0) {
		tmpMN = window.setTimeout("window.document.getElementById('"+id+"').style.visibility = 'hidden';",800);
	}
	
}
function setDiv(id,style,value) {
	eval("window.document.getElementById('"+id+"').style."+style+"='"+value+"';");
}