//||||||||||||| FUNÇÃO CHECKA EMAIL ||||||||||||||||||
function emailCheck (emailStr,nome_campo) {

var emailPat=/^(.+)@(.+)$/
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
var validChars="\[^\\s" + specialChars + "\]"
var firstChars=validChars
var quotedUser="(\"[^\"]*\")"
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
var atom="(" + firstChars + validChars + "*" + ")"
var word="(" + atom + "|" + quotedUser + ")"
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")

var matchArray=emailStr.match(emailPat)
if (matchArray==null && document.getElementById(nome_campo).value!="") {
	   alert("Endereço incorreto (verifique @ e .'s)")
	   document.getElementById(nome_campo).value="";
	   document.getElementById(nome_campo).focus();		
	   return false
}
var user=matchArray[1]
var domain=matchArray[2]

if (user.match(userPat)==null ) {
    // user is not valid
    alert("E-mail não válido.")
	 document.getElementById(nome_campo).value="";
	 document.getElementById(nome_campo).focus();
    return false
}

var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	        alert("Destination IP address is invalid!")
			  document.getElementById(nome_campo).value="";
			  document.getElementById(nome_campo).focus();
		     return false
	    }
    }

    //document.form.submit()
}

var domainArray=domain.match(domainPat)
if (domainArray==null) {
	alert("O domínio do e-mail não é válido!")
	document.getElementById(nome_campo).value="";
	document.getElementById(nome_campo).focus();
    return false
}

var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 || 
    domArr[domArr.length-1].length>3) {
   alert("O final do endereço está incorreto")
	document.getElementById(nome_campo).value="";
	document.getElementById(nome_campo).focus();
   return false
}


if (domArr[domArr.length-1].length==3 && len<2) {
   var errStr="Endereço Inválido!"
   alert(errStr)
	document.getElementById(nome_campo).value="";
	document.getElementById(nome_campo).focus();
   return false
}
    //document.form.submit();

}
//||||||||||||| FIM FUNÇÃO CHECKA EMAIL |||||||||||||||||

//|||||||||||| FUNÇÃO DETECTA CAMPOS VAZIOS CADASTRO CLIENTE ADMIN |||||||||||
function verifica(v){
	
   if(navigator.appName =="Microsoft Internet Explorer"){   
		if(v!="x"){
	      if(navigator.appName =="Microsoft Internet Explorer"){
			   // Se a chamada vier dos próprios campos
		      for (i=0;i<18;i++){		            
	            if(document.form1.elements[v-1].value==""){
			         if(navigator.appName !="Microsoft Internet Explorer"){
	                  alert('preencha o campo '+	document.form1.elements[v+1].name);	
				      }else{					
				          alert('preencha o campo '+	document.forms[0].getElementsByTagName('B')[v].innerHTML);					
				      }	
					   if(document.form1.elements[v].value==""){			
				         document.form1.elements[v].value="";
					   }
					   d=1
				      document.form1.elements[v-1].focus();					   
				      return false										
		         }else{
			         if(d!=1){
		               document.form1.submit()	    
				      } 
		         }		  
	         }			      
	      }
			
		}else if(v=="x"){
			// Se a chamada vier do submit	   
		   for (i=0;i<16;i++){		
            if(i==5 || i==9 || i==10 ||i==11 || i==12 ){
			      continue;
			   }
	         if(document.form1.elements[i].value==""){
			      if(navigator.appName !="Microsoft Internet Explorer"){
	               alert('preencha o campo '+	document.form1.elements[i].name);	
			      }else{					
				      alert('preencha o campo '+	document.forms[0].getElementsByTagName('B')[i+1].innerHTML + " "+i);					
				   }	
				   d=1				
				   document.form1.elements[i].focus();					   
				   return false																
		      }else{
			      if(d!=1){
		            document.form1.submit()	    
				   } 
		      }		  
	      }						
		}	
	}

}
//|||||||||| FIM FUNÇÃO DETECTA CAMPOS VAZIOS CADASTRO CLIENTE ADMIN ||||||||||||||

//||||||FUNÇAO CAMPOS VAZIOS ATIVIDADE SERVIÇO ||||||||||||||
function verifica2(){

   if(document.form1.elements[0].value=="" || document.form1.elements[1].value==""){
	   alert('preencha todos o campo acima')
	   return false;
	}
}

function verifica3(){

   if(document.form3.elements[0].value=="" || document.form3.elements[1].value==""){
	   alert('preencha todos o campo acima')
	   return false;
	}
}

//||||| FIM FUNÇAO CAMPOS VAZIOS ATIVIDADE SERVIÇO ||||||||||||||

//||||||||||| VALIDA TELEFONE ||||||||||||||||||||||||||
function valida_fone(campo_fone){
	s= document.getElementById(campo_fone).value;
	if( !s.match(/[0-9][0-9][0-9]\-[0-9][0-9][0-9][0-9]$/)&&            
	    document.getElementById(campo_fone).value !=""  ){
			  
	   alert('Por favor siga o modelo ao lado do campo\n'+
		      'e não deixe espaços vazios. \n\n'+
			   'Exemplo (71)443-1250 ou 433-1250\n'+
			   'ou aínda (73)4432-1250 ou 4332-1250')
				
		document.getElementById(campo_fone).value = "";
		document.getElementById(campo_fone).focus();
		
		return false;
	}				
   return true;
}
//||||||||||||||| FIM VALIDA TELEFONE ||||||||||||||||||

//|||||| LIMITA CARACTERES ||||||||||||||||||
/***********************************************
* Form Field Progress Bar- By Ron Jonk- http://www.euronet.nl/~jonkr/
* Modified by Dynamic Drive for minor changes
* Script featured/ available at Dynamic Drive- http://www.dynamicdrive.com
* Please keep this notice intact
***********************************************/

function textCounter(field,counter,maxlimit,linecounter) {
	// text width//
	var fieldWidth =  parseInt(field.offsetWidth);
	var charcnt = field.value.length;        

	// trim the extra text
	if (charcnt > maxlimit) { 
		field.value = field.value.substring(0, maxlimit);
	}

	else { 
	// progress bar percentage
	var percentage = parseInt(100 - (( maxlimit - charcnt) * 100)/maxlimit) ;
	document.getElementById(counter).style.width =  parseInt((fieldWidth*percentage)/100)+"px";
	document.getElementById(counter).innerHTML="Limit: "+percentage+"%"
	// color correction on style from CCFFF -> CC0000
	setcolor(document.getElementById(counter),percentage,"background-color");
	}
}

function setcolor(obj,percentage,prop){
	obj.style[prop] = "rgb(80%,"+(100-percentage)+"%,"+(100-percentage)+"%)";
}

//||||||| FIM LIMITA CARACTERES ||||||||||||||||||


//||||||| FUNÇÃO TRAVA BOTÃO DIREITO ||||||||||||||||||||
/*
function verfonte(){
   if (event.button==2){
      //window.alert('Desculpe-me mas ó código não pode ser exibido!')
   }
}
document.onmousedown=verfonte
*/
//||||||| FIM FUNÇÃO TRAVA BOTÃO DIREITO ||||||||||||||||||||



//|||||||| CONFIRMAÇÃO DE EXCLUSÃO DE ESTADOS ||||||||||||||||||

function aviso(nome1){   
   if(confirm('Tem certeza que quer deletar esse registro?')){    
      alert('Então continue o processo.\ndepois de clicado o botão\n'+
	   '\"Deletar\".\n os dados não poderão ser recuperados')
	   nome1.checked= true;
	   return false;
   }else{
      nome1.checked= false;	 
   }
}  


//|||||||||| OCULTA DETERMINADOS CAMPOS DE ACORDO COM O PLANO ESCOLHIDO |||||||		
/*
function oculta(){   
   resultado=document.getElementById('status_cli').value	
	if(resultado=="basico"){ 	     
		document.getElementById('foto1').style.display="none";
		document.getElementById('foto2').style.display="none";
		document.getElementById('foto3').style.display="none";
		document.getElementById('foto4').style.display="none";
		document.getElementById('mensagem_cli').style.display="none";
	}else if(resultado=="destaque" || resultado=="filiado"){	   
	   document.getElementById('foto1').style.display="none";
		document.getElementById('foto2').style.display="none";
		document.getElementById('foto3').style.display="none";
		document.getElementById('foto4').style.display="none";
		document.getElementById('mensagem_cli').style.display="none";		
	}else if(resultado=="master"){
	   document.getElementById('foto1').style.display="inline";
		document.getElementById('foto2').style.display="none";
		document.getElementById('foto3').style.display="none";
		document.getElementById('foto4').style.display="none";
		document.getElementById('mensagem_cli').style.display="inline";
	}else if(resultado=="ouro"){	   
	   document.getElementById('foto1').style.display="inline";
		document.getElementById('foto2').style.display="inline";
		document.getElementById('foto3').style.display="inline";
		document.getElementById('foto4').style.display="inline";
		document.getElementById('mensagem_cli').style.display="inline";
	}
}
*/
//Funcão aviso deletar só Pagos
var contar=0;
function pago(sit){
   if(sit!="Pago"){
	   alert('Desculpe! mas você só pode deletar parcelas pagas.')
	}  
	contar++; 
}

/////////||||||| DATA ||||||||||||||//////////

        hoje = new Date()


        dia = hoje.getDate()


        dias = hoje.getDay()


        mes = hoje.getMonth()


        ano = hoje.getYear()


        if (dia < 10)


                dia = "0" + dia


        if (ano < 2000)


                ano = 1900 + ano


        function CriaArray (n) {


        this.length = n }


        NomeDia = new CriaArray(7)


        NomeDia[0] = "Domingo"


        NomeDia[1] = "Segunda-feira"


        NomeDia[2] = "Ter&ccedil;a-feira"


        NomeDia[3] = "Quarta-feira"


        NomeDia[4] = "Quinta-feira"


        NomeDia[5] = "Sexta-feira"


        NomeDia[6] = "S&aacute;bado"


 


        NomeMes = new CriaArray(12)


        NomeMes[0] = "Janeiro"


        NomeMes[1] = "Fevereiro"


        NomeMes[2] = "Mar&ccedil;o"


        NomeMes[3] = "Abril"


        NomeMes[4] = "Maio"


        NomeMes[5] = "Junho"


        NomeMes[6] = "Julho"


        NomeMes[7] = "Agosto"


        NomeMes[8] = "Setembro"


        NomeMes[9] = "Outubro"


        NomeMes[10] = "Novembro"


        NomeMes[11] = "Dezembro"





function WriteDate(cor,cidade) {


        document.write ("<span class="+cor+">"+cidade+" " + NomeDia[dias] +  " " + dia + " de " + NomeMes[mes] + " de " + ano+"</span>" )


}

/////////||||||| FIM DATA ||||||||||||||//////////

// ======= FAVORITOS ========

function favoritos(){
   url="http://www.feiraodosveiculos";
	titulo="Feirão dos veículos.com.br";
	window.external.AddFavorite(url,titulo);
}

// Função para texto da dica como usar o campo "Palavras Chave"
function p_chave_dica(){
   alert('O que for escrito nesse campo, não aparecerá para o cliente '+
	       'é apenas para o mecanismo de busca, então, use palavras soltas '+
			 'as quais você acredita que  o usuário irá digitar, ao procurar '+
			 'uma loja ou profissão igual a sua')
}

///////|||||||||||||| SUBSTITUE CARACTERES |||||||||||||||||////////////

function muda_chr(chave){	   
   tx=document.getElementById(chave).value
	vari=tx.substring((tx.length)-1,(tx.length))
	vari2=vari.charCodeAt(vari.substring((vari.length)-1,(vari.length)))
	
	completa="";
	c="´"
	
	if(c.charCodeAt(0)==180){completa=c}
	if(vari2==39){	   
	   novo=tx.substring(0,(tx.length)-1)+completa;
	   document.getElementById(chave).value=novo;
	}
}

////////||||||||||||| VALIDA MOEDA |||||||||||||||||||/////////////

	// Não permite inserir vírgula nem mais de um ponto
	ic=0;
	ci=0;
	ct=0;
	ct2=0;
	function valida_moeda(ID){	   
	   cha=document.getElementById(ID).value		
	   
		//Verifica se não foram digitadas letras
		if(isNaN(cha)&& cha.match(/[0-9]/)){
		   alert('Use apenas números e ponto para separar os centavos'+
			      '\nNão use letras ou vírgula'
				   )
			document.getElementById(ID).value=""
		}else if(isNaN(cha) && !cha.match(/[.]/)){
		   alert('Use apenas números e ponto para separar os centavos'+ 
			      '\nNão use letras ou vírgula'
			      )
			document.getElementById(ID).value=""
		}else{
		
		}
		
	}  
		
	// onkeyup="valida_moeda(ID)"
	////////|||||||||| FIM  VALIDA MOEDA |||||||||||||||||||/////////////

	
/// ||||||||||||| PROIBE HOTMAIL ||||||||||||||||||||||||
var proibe= new Array();
var avisa= new Array();
proibe[0]="@hotmail.com"
avisa[0]="sim"
proibe[1]="@hotmail.com"
avisa[1]="sim"

//Obs: o array avisa,decide se um alerta será aberto "sim" ou "nao" avisando
// que o termo não pode ser usado, esse recurso é individual para cada termo

function detecta_email2(valor,op){    
   var anyString=document.getElementById(valor).value	   
	for(contar=0;contar<=proibe.length;contar++){
	   if(anyString.indexOf(proibe[contar])>-1){
		   if(avisa[contar]=="sim" && op!="1"){
	         alert('Emails do: '+ proibe[contar]+' podem não ser aceitos')
			}
			if( op=="1"){
			   if(avisa[contar]=="sim"){
			      alert('Desculpe! Não é aceito emails do: '+ proibe[contar])
				}
		      document.getElementById(valor).value=""
			}
	   }
	}
}

//||||| Revezamento das fotos poupup financiamento
function muda_foto(minha_foto){	
   document.getElementById('mfoto').src='admin/imgs/produtos/'+minha_foto
}


//||||||||||||||| MÁSCARA PARA VALORES EM GERAL ||||||||||||||||||||||||

function txtBoxFormat(objeto, sMask, evtKeyPress) {
    var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;


if(document.all) { // Internet Explorer
    nTecla = evtKeyPress.keyCode;
} else if(document.layers) { // Nestcape
    nTecla = evtKeyPress.which;
} else {
    nTecla = evtKeyPress.which;
    if (nTecla == 8) {
        return true;
    }
}

    sValue = objeto.value;

    // Limpa todos os caracteres de formatação que
    // já estiverem no campo.
    sValue = sValue.toString().replace( "-", "" );
    sValue = sValue.toString().replace( "-", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( ":", "" );
    sValue = sValue.toString().replace( ":", "" );
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( " ", "" );
    sValue = sValue.toString().replace( " ", "" );
    fldLen = sValue.length;
    mskLen = sMask.length;

    i = 0;
    nCount = 0;
    sCod = "";
    mskLen = fldLen;

    while (i <= mskLen) {
      bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/") || (sMask.charAt(i) == ":"))
      bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

      if (bolMask) {
        sCod += sMask.charAt(i);
        mskLen++; }
      else {
        sCod += sValue.charAt(nCount);
        nCount++;
      }

      i++;
    }

    objeto.value = sCod;

    if (nTecla != 8) { // backspace
       if (sMask.charAt(i-1) == "9") { // apenas números...
          return ((nTecla > 47) && (nTecla < 58)); 
		 }else if (sMask.charAt(i-1) == "a"){
		    return ((nTecla > 96) && (nTecla < 123));
       }else { // qualquer caracter...
          return true;
       }
    }
    else {
      return true;
    }
  }
  // EXEMPLO: onkeypress="return txtBoxFormat(this, 'AAA-9999', event);"
  
 //||||||||||||| FIM MÁSCARA PARA VALORES EM GERAL ||||||||||||||||||||||
  
 //|||||||||||||| MÁSCARA PARA VALORES MONETÁRIOS |||||||||||||||||||||||
 /**
 *
 * function currencyFormat(fld, milSep, decSep, e)
 *
 * fld    = Objeto a ser verficado.
 * milSep = Separador para milhar.
 * decSep = Separador para decimal.
 * e      = Evento.
 *
 * Formata um valor decimal conforme for digitado no box (Ex:1.234.566,00).
 * Criação: Anonima (coletada em http://http://www.scriptbrasil.com/?class=2&secao=javascript&categoria=Formulários&menu=javascript&ini=1
 * Revisao: pedro.leao@ig.com.br	2003/08/16
 * Exemplos:
 * <input type="text" name="test" length=15 onKeyPress="return(currencyFormat(this,'.',',',event))">
 * <input type="text" name="test2" length=15 onKeyPress="return(currencyFormat(this,'','.123',event))"> 
 *
 */
function currencyFormat(fld, milSep, decSep, e) {
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;

	if (whichCode == 13) {
		return true;  // Enter
	}
	key = String.fromCharCode(whichCode);  // Get key value from key code
	if (strCheck.indexOf(key) == -1) {
		return false;  // Not a valid key
	}
	len = fld.value.length;
	for(i = 0; i < len; i++) {
		if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)){
			 break;
		}
	}
	
	aux = '';
	for(; i < len; i++) {
		if (strCheck.indexOf(fld.value.charAt(i))!=-1){
			aux += fld.value.charAt(i);
		}
	}
	aux += key;
			
	len = aux.length;
	if (len == 0) {
		fld.value = '';
	} else if (len == 1) {
		fld.value = '0'+ decSep + '0' + aux;
	} else if (len == 2) {
		fld.value = '0'+ decSep + aux;
	} else if (len > 2) {
		aux2 = '';

		for (j = 0, i = len - 3; i >= 0; i--) {
			if (j == 3) {
				aux2 += milSep;
				j = 0;
			}
			aux2 += aux.charAt(i);
			j++;
		}
		fld.value = '';
		len2 = aux2.length;
		for (i = len2 - 1; i >= 0; i--) {
			fld.value += aux2.charAt(i);
		}
		
		fld.value += decSep + aux.substr(len - 2, len);
	}
	return false;
}
 //||||||||||||||||| FIM MÁSCARA PARA VALORES |||||||||||||||||||||||||||
 
/// ||||||||||||| PROIBE HOTMAIL ||||||||||||||||||||||||
var proibe= new Array();
var avisa= new Array();
proibe[0]="@hotmail.com"
avisa[0]="sim"
proibe[1]="--"
avisa[1]="sim"

//Obs: o array avisa,decide se um alerta será aberto "sim" ou "nao" avisando
// que o termo não pode ser usado, esse recurso é individual para cada termo
//Ex onkeyup="detecta_email('email_cli')"
function detecta_email(valor){    
   var anyString=document.getElementById(valor).value	   
	for(contar=0;contar<=proibe.length;contar++){
	   if(anyString.indexOf(proibe[contar])>-1){
		   if(avisa[contar]=="sim"){
	         alert('Desculpe! Não é aceito: '+ proibe[contar])
			}
		   document.getElementById(valor).value=""
	   }
	}
}

// ||||||||||||| DICA PARA COMBINAÇÕES DE CORES
function dica_cores(){
   alert(
	   'Procure fazer uma combinação em que todas as amostras de cores fiquem com\n'+
		'texto e fundo destacados. Se usando todas as cores da sua empresa, isso não for possível, '+
		'tente usar variações de tonalidade, por exemplo:azul escuro com azul mais claro.\n'+
		'De qualquer forma você poderá visualizar e depois mudar as cores caso não esteja a seu gosto.'
	)
}

//||||||||||||||FUNÇÃO PARA EXTRAIR ENDEREÇO DE VIDEODO CÓDIGO DO YOUTUBE
function preenche(){	     
		 
		 document.getElementById('conteudo').innerHTML=document.getElementById('cod').value
		
		 str=document.getElementById('cod').value			 

       re = /(http:\/\/www.youtube.com\/(.)*\&\">)/g;
    
      found = str.match(re);

		found= found.toString().replace( "\">", "" );
		
      document.getElementById('end_video').value=found	
      testa=1;
			   
		}
