// JavaScript Document

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 limpa_campo(qual, texto, tipo){
		var element = document.getElementById(qual);
	if(element.value=='' && tipo=='out'){
		element.value=texto;
	}else if(element.value==texto && tipo=='in'){
		element.value='';
	}
}

// Início do código de Aumentar/ Diminuir a letra
 
// Para usar coloque o comando: "javascript:mudaTamanho('tag_ou_id_alvo', -1);" para diminuir
// e o comando "javascript:mudaTamanho('tag_ou_id_alvo', +1);" para aumentar
 
var tagAlvo = new Array('p'); //pega todas as tags p//
 
// Especificando os possíveis tamanhos de fontes, poderia ser: x-small, small...
var tamanhos = new Array( '9px','10px','11px','12px','13px','14px','15px' );
var tamanhoInicial = 2;
 
function mudaTamanho( idAlvo,acao ){
  if (!document.getElementById) return
  var selecionados = null,tamanho = tamanhoInicial,i,j,tagsAlvo;
  tamanho += acao;
  if ( tamanho < 0 ) tamanho = 0;
  if ( tamanho > 6 ) tamanho = 6;
  tamanhoInicial = tamanho;
  if ( !( selecionados = document.getElementById( idAlvo ) ) ) selecionados = document.getElementsByTagName( idAlvo )[ 0 ];
  
  selecionados.style.fontSize = tamanhos[ tamanho ];
  
  for ( i = 0; i < tagAlvo.length; i++ ){
    tagsAlvo = selecionados.getElementsByTagName( tagAlvo[ i ] );
    for ( j = 0; j < tagsAlvo.length; j++ ) tagsAlvo[ j ].style.fontSize = tamanhos[ tamanho ];
  }
}


//script para abrir popup
function OpenWindow(FileNameToOpen,janela,largura,altura)
{
newWindow = window.open(FileNameToOpen,janela, 'width='+largura+', height='+altura+', toolbar=no, scrollbars=yes, location=no, left=100, top=100')
if (newWindow.open)
{
newWindow.focus()
}
}

function ajaxValidator() {
  //verifica se o browser tem suporte a ajax
  try {
	 ajax = new ActiveXObject("Microsoft.XMLHTTP");
  } 
  catch(e) {
	 try {
		ajax = new ActiveXObject("Msxml2.XMLHTTP");
	 }
	 catch(ex) {
		try {
		   ajax = new XMLHttpRequest();
		}
		catch(exc) {
		   alert("Esse browser não tem recursos para uso do Ajax");
		   ajax = null;
		}
	 }
  }

	return ajax;	
}	

// FUNCAO QUE EXIBE AS SUB-CATEGORIAS
function Dados(valor) {
   
  var ajax = ajaxValidator();
   
  //se tiver suporte ajax
  if(ajax) {
	 //deixa apenas o elemento 1 no option, os outros são excluídos
	 document.formFiltro.SubCategoria.options.length = 1;
	 
	 idOpcao  = document.getElementById("opcoes");
	 
	 ajax.open("POST", "e_selcsubcategoria.php", true);
	 ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	 
	 ajax.onreadystatechange = function() {
		//enquanto estiver processando...emite a msg de carregando
		if(ajax.readyState == 1) {
		   idOpcao.innerHTML = "Carregando...!";   
		}
		//após ser processado - chama função processXML que vai varrer os dados
		if(ajax.readyState == 4 ) {
		   if(ajax.responseXML) {
			  processXML(ajax.responseXML);
		   }
		   else {
			   //caso não seja um arquivo XML emite a mensagem abaixo
			   idOpcao.innerHTML = "SELECIONE A CATEGORIA";
		   }
		}
	 }
	 //passa o código da categoria escolhida
	 var params = "categoria="+valor;
	 ajax.send(params);
  }
}

function processXML(obj) {
  //pega a tag subcategoria
  var dataArray = obj.getElementsByTagName("subcategoria");
  
  //total de elementos contidos na tag subcategoria
  if(dataArray.length > 0) {
	 //percorre o arquivo XML para extrair os dados
	 for(var i = 0 ; i < dataArray.length ; i++) {
		var item = dataArray[i];
		//contéudo dos campos no arquivo XML
		var codigo    =  item.getElementsByTagName("id")[0].firstChild.nodeValue;
		var descricao =  item.getElementsByTagName("nome")[0].firstChild.nodeValue;
		
		idOpcao.innerHTML = "CLIQUE AQUI!";
		
		//cria um novo option dinamicamente  
		var novo = document.createElement("option");
			//atribui um ID a esse elemento
			novo.setAttribute("id", "opcoes");
			//atribui um valor
			novo.value = codigo;
			//atribui um texto
			novo.text  = descricao;
			//finalmente adiciona o novo elemento
			document.formFiltro.SubCategoria.options.add(novo);
	 }
  }
  else {
	//caso o XML volte vazio, printa a mensagem abaixo
	idOpcao.innerHTML = "NÃO HÁ SUBCATEGORIA CADASTRADA";
  }	  
}	



// FUNCAO QUE EXIBE AS SUB-CATEGORIAS
function Dados1(valor) {
   
  var ajax = ajaxValidator();
   
  //se tiver suporte ajax
  if(ajax) {
	 //deixa apenas o elemento 1 no option, os outros são excluídos
	 document.formFiltro.Categoria.options.length = 1;
	 
	 idOpcao  = document.getElementById("opcoes1");
	 
	 ajax.open("POST", "e_selccategoria.php", true);
	 ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	 
	 ajax.onreadystatechange = function() {
		//enquanto estiver processando...emite a msg de carregando
		if(ajax.readyState == 1) {
		   idOpcao.innerHTML = "Carregando...!";   
		}
		//após ser processado - chama função processXML que vai varrer os dados
		if(ajax.readyState == 4 ) {
		   if(ajax.responseXML) {
			  processXML1(ajax.responseXML);
		   }
		   else {
			   //caso não seja um arquivo XML emite a mensagem abaixo
			   idOpcao.innerHTML = "SELECIONE O SEGMENTO";
		   }
		}
	 }
	 //passa o código da categoria escolhida
	 var params = "segmento="+valor;
	 ajax.send(params);
  }
}

function processXML1(obj) {
  //pega a tag subcategoria
  var dataArray = obj.getElementsByTagName("categoria");
  
  //total de elementos contidos na tag subcategoria
  if(dataArray.length > 0) {
	 //percorre o arquivo XML para extrair os dados
	 for(var i = 0 ; i < dataArray.length ; i++) {
		var item = dataArray[i];
		//contéudo dos campos no arquivo XML
		var codigo    =  item.getElementsByTagName("id")[0].firstChild.nodeValue;
		var descricao =  item.getElementsByTagName("nome")[0].firstChild.nodeValue;
		
		idOpcao.innerHTML = "CLIQUE AQUI!";
		
		//cria um novo option dinamicamente  
		var novo = document.createElement("option");
			//atribui um ID a esse elemento
			novo.setAttribute("id", "opcoes1");
			//atribui um valor
			novo.value = codigo;
			//atribui um texto
			novo.text  = descricao;
			//finalmente adiciona o novo elemento
			document.formFiltro.Categoria.options.add(novo);
	 }
  }
  else {
	//caso o XML volte vazio, printa a mensagem abaixo
	idOpcao.innerHTML = "NÃO HÁ CATEGORIA CADASTRADA";
  }	  
}

function Formatar_Telefone(objeto,tammax,teclapres){

    var tecla = teclapres.keyCode;
    vr = objeto.value;
    vr = vr.replace( "(", "" );
    vr = vr.replace( ")", "" );
    vr = vr.replace( " ", "" );
    vr = vr.replace( "-", "" );
    tam = vr.length;

    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 <= 4 ) {
                     objeto.value = vr ;
            }
             if ( (tam > 4) && (tam <= 8) ) {
                     objeto.value = vr.substr(0,tam-4) + '-' + vr.substr( tam - 4, tam ) ;
            }
             if ( (tam >= 9) && (tam <= 10) ) {
                    objeto.value = '(' + vr.substr(0,2) + ') ' + vr.substr(2,tam-6) + '-' + vr.substr(tam-4,tam) ;
            }
    }
}

function Validar_Email(email){

    if(email.length < 6) {
            return false;
    }

    var x = 0;
    for (var c=0;c<email.length;c++) {
            if (email.substring(c,c+1) == '@') {
                    x = c;
            }
    }
    var y = 0;
    if (x > 0) {
            for (c=x;c<email.length;c++) {
                    if (email.substring(c,c+1)=='.') {
                            y = c;
                            var valida = 1;
                    }
            }
            if (y > 0) {
                    var dominio = '';
                    for (c=x;c<y;c++) {
                            dominio = dominio + email.substring(1,c);
                    }
            }
    }
    else {
            return false;
    }
    if (y <= x+2){
            return false;
    }
    if (valida == 1){
            return true;
    }
}

function Validar_EditCadastro(){
    
	if (document.formCad.nome.value=="") {
            document.formCad.nome.focus();
            alert("Digite seu nome!");
            return false;
    }	
	
    if (document.formCad.email.value=="") {
            document.formCad.email.focus();
            alert("Informe o seu e-mail!");
            return false;
    } else {
            if (!Validar_Email(document.formCad.email.value)) {
                    document.formCad.email.focus();
                    alert("Digite um e-mail válido!");
                    return false;
            }
    }	        
	
	if (document.formCad.endereco.value=="") {
            document.formCad.endereco.focus();
            alert("Digite o nome da sua rua!");
            return false;
    }	
	
	if (document.formCad.n.value=="") {
            document.formCad.n.focus();
            alert("Digite o número da sua casa!");
            return false;
    }	
	
	if (document.formCad.telefone.value=="") {
            document.formCad.telefone.focus();
            alert("Digite o número de telefone!");
            return false;
    }	
            
	if (document.formCad.bairro.value=="") {
            document.formCad.bairro.focus();
            alert("Digite o nome do seu bairro!");
            return false;
    }	
			
	if (document.formCad.cidade.value=="") {
            document.formCad.cidade.focus();
            alert("Digite o nome da sua cidade!");
            return false;
    }	       		
    
	if (document.formCad.obra.value=="") {
            document.formCad.obra.focus();
            alert("Informe o tipo da obra!");
            return false;
    }	        

	if (document.formCad.senha01.value!="" || document.formCad.senha02.value!="") {
        
		var senha01 = document.formCad.senha01.value;    
		var senha02 = document.formCad.senha02.value;
		
		if(senha01 != senha02) {
			document.formCad.senha01.focus();
            alert("As senhas não são iguais!");
            return false;
		}
    }                 
            
}	

function Validar_Cadastro(){
    
	if (document.formCad.nome.value=="") {
            document.formCad.nome.focus();
            alert("Digite seu nome!");
            return false;
    }	
	
    if (document.formCad.email.value=="") {
            document.formCad.email.focus();
            alert("Informe o seu e-mail!");
            return false;
    } else {
            if (!Validar_Email(document.formCad.email.value)) {
                    document.formCad.email.focus();
                    alert("Digite um e-mail válido!");
                    return false;
            }
    }	        
	
	if (document.formCad.endereco.value=="") {
            document.formCad.endereco.focus();
            alert("Digite o nome da sua rua!");
            return false;
    }	
	
	if (document.formCad.n.value=="") {
            document.formCad.n.focus();
            alert("Digite o número da sua casa!");
            return false;
    }	
	
	if (document.formCad.telefone.value=="") {
            document.formCad.telefone.focus();
            alert("Digite o número de telefone!");
            return false;
    }	
            
	if (document.formCad.bairro.value=="") {
            document.formCad.bairro.focus();
            alert("Digite o nome do seu bairro!");
            return false;
    }	
			
	if (document.formCad.cidade.value=="") {
            document.formCad.cidade.focus();
            alert("Digite o nome da sua cidade!");
            return false;
    }	        		
    
	if (document.formCad.obra.value=="") {
            document.formCad.obra.focus();
            alert("Informe o tipo da obra!");
            return false;
    }	
    
    
	if (document.formCad.senha01.value=="") {
            document.formCad.senha01.focus();
            alert("Digite a sua senha!");
            return false;
    }        
        
    
	if (document.formCad.senha02.value=="") {
            document.formCad.senha02.focus();
            alert("Confirme a sua senha!");
            return false;
    }  

	if (document.formCad.senha01.value!="" && document.formCad.senha02.value!="") {
        
		var senha01 = document.formCad.senha01.value;    
		var senha02 = document.formCad.senha02.value;
		
		if(senha01 != senha02) {
			document.formCad.senha01.focus();
            alert("As senhas não são iguais!");
            return false;
		}
    }                 
            
}

function Validar_Cadastro2(){
    
	if (document.formCad.nome.value=="") {
            document.formCad.nome.focus();
            alert("Digite seu nome!");
            return false;
    }	
	
    if (document.formCad.email.value=="") {
            document.formCad.email.focus();
            alert("Informe o seu e-mail!");
            return false;
    } else {
            if (!Validar_Email(document.formCad.email.value)) {
                    document.formCad.email.focus();
                    alert("Digite um e-mail válido!");
                    return false;
            }
    }	        
	
	if (document.formCad.telefone.value=="") {
            document.formCad.telefone.focus();
            alert("Digite o número de telefone!");
            return false;
    }	
                    
}

function validaPedido() {
	
	if (document.FormCarrinho.vendedor.value == "") {
      
		document.FormCarrinho.vendedor.focus();
        alert("Escolha um vendedor!");
        return false;
        
	} else {
		
		if(confirm('Deseja mesmo efetivar esse orçamento?')) {
		    return true;
		} else {
			return false;
		}		
		
	}	
}