// JavaScript Document
function validaCNPJ(testaCNPJ) {
	CNPJ = testaCNPJ;
    erro = new String;
    if (CNPJ.length < 18) erro += "É necessario preencher corretamente o número do CPF/CNPJ! \n\n"; 
    if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
    if (erro.length == 0) erro += "É necessário preencher corretamente o número do CPF/CNPJ! \n\n";
    }
    if (CNPJ == "000000000000000" || CNPJ == "111111111111111" || CNPJ == "222222222222222" || CNPJ == "333333333333333" || CNPJ == "444444444444444" || CNPJ == "555555555555555" || CNPJ == "666666666666666" || CNPJ == "777777777777777" || CNPJ == "888888888888888" || CNPJ == "999999999999999"){
			  erro += "Numero de CNPJ invalido!"
		}
	//substituir os caracteres que n&atilde;o s&atilde;o números
    if(document.layers && parseInt(navigator.appVersion) == 4){
    	x = CNPJ.substring(0,2);
        x += CNPJ. substring (3,6);
        x += CNPJ. substring (7,10);
        x += CNPJ. substring (11,15);
        x += CNPJ. substring (16,18);
        CNPJ = x; 
    } else {
		CNPJ = CNPJ. replace (".","");
        CNPJ = CNPJ. replace (".","");
        CNPJ = CNPJ. replace ("-","");
        CNPJ = CNPJ. replace ("/","");
	}
    var nonNumbers = /\D/;
    if (nonNumbers.test(CNPJ)) erro += "A verifica&ccedil;&atilde;o de CNPJ suporta apenas números! \n\n"; 
    	var a = [];
        var b = new Number;
        var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
        for (i=0; i<12; i++){
        	a[i] = CNPJ.charAt(i);
            b += a[i] * c[i+1];
		}
        if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
			b = 0;
            for (y=0; y<13; y++) {
            	b += (a[y] * c[y]); 
       	}
        if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
        	if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
                       erro +="Dígito verificador com problema!";
            }
            if (erro.length > 0){
                       alert(erro);
                       return false;
			}
            return true;
		}

function validaCPF() {
	cpf = document.forms[0].cad_CPF_CNPJ.value; 
	valor = true;
	erro = new String;
	if (cpf.length < 11) erro += "Sao necessarios 11 digitos para verificacao do CPF! \n\n"; 
		var nonNumbers = /\D/;
		if (nonNumbers.test(cpf)) erro += "A verificacao de CPF suporta apenas numeros! \n\n";	
		if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){
			  erro += "Numero de CPF invalido!"
		}
		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])){
			erro +="Digito verificador com problema!";
		}
		if (erro.length > 0){
			validaCNPJ(cpf);
		} 
		
		return true;
	}

function MM_callJS(jsStr) { //v2.0
  return eval(jsStr)
}

function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}

//abrir janela Pop-up
function MM_openBrWindow(theURL,winName,features) { //v2.0
	window.open(theURL,winName,features);
}

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_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 MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}

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;
}

// validação de formulário

function YY_checkform() { //v4.71
//copyright (c)1998,2002 Yaromat.com
  var a=YY_checkform.arguments,oo=true,v='',s='',err=false,r,o,at,o1,t,i,j,ma,rx,cd,cm,cy,dte,at;
  for (i=1; i<a.length;i=i+4){
    if (a[i+1].charAt(0)=='#'){r=true; a[i+1]=a[i+1].substring(1);}else{r=false}
    o=MM_findObj(a[i].replace(/\[\d+\]/ig,""));
    o1=MM_findObj(a[i+1].replace(/\[\d+\]/ig,""));
    v=o.value;t=a[i+2];
    if (o.type=='text'||o.type=='password'||o.type=='hidden'||o.type=='file'){
      if (r&&v.length==0){err=true}
      if (v.length>0)
      if (t==1){ //fromto
        ma=a[i+1].split('_');if(isNaN(v)||v<ma[0]/1||v > ma[1]/1){err=true}
      } else if (t==2){
        rx=new RegExp("^[\\w\.=-]+@[\\w\\.-]+\\.[a-zA-Z]{2,4}$");if(!rx.test(v))err=true;
      } else if (t==3){ // date
        ma=a[i+1].split("#");at=v.match(ma[0]);
        if(at){
          cd=(at[ma[1]])?at[ma[1]]:1;cm=at[ma[2]]-1;cy=at[ma[3]];
          dte=new Date(cy,cm,cd);
          if(dte.getFullYear()!=cy||dte.getDate()!=cd||dte.getMonth()!=cm){err=true};
        }else{err=true}
      } else if (t==4){ // time
        ma=a[i+1].split("#");at=v.match(ma[0]);if(!at){err=true}
      } else if (t==5){ // check this 2
            if(o1.length)o1=o1[a[i+1].replace(/(.*\[)|(\].*)/ig,"")];
            if(!o1.checked){err=true}
      } else if (t==6){ // the same
            if(v!=MM_findObj(a[i+1]).value){err=true}
      }
    } else
    if (!o.type&&o.length>0&&o[0].type=='radio'){
          at = a[i].match(/(.*)\[(\d+)\].*/i);
          o2=(o.length>1)?o[at[2]]:o;
      if (t==1&&o2&&o2.checked&&o1&&o1.value.length/1==0){err=true}
      if (t==2){
        oo=false;
        for(j=0;j<o.length;j++){oo=oo||o[j].checked}
        if(!oo){s+='* '+a[i+3]+'\n'}
      }
    } else if (o.type=='checkbox'){
      if((t==1&&o.checked==false)||(t==2&&o.checked&&o1&&o1.value.length/1==0)){err=true}
    } else if (o.type=='select-one'||o.type=='select-multiple'){
      if(t==1&&o.selectedIndex/1==0){err=true}
    }else if (o.type=='textarea'){
      if(v.length<a[i+1]){err=true}
    }
    if (err){s+='* '+a[i+3]+'\n'; err=false}
  }
  if (s!=''){alert('As informações abaixo são necessárias ou contém erros:\t\t\t\t\t\n\n'+s)}
  document.MM_returnValue = (s=='');
}


function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

function changeCPF(){
	fld=document.getElementById("cad_pais");
	cod=parseInt(fld[fld.selectedIndex].value);
	switch(cod){
	 case 30:
		document.getElementById("label_CPF").innerHTML="CPF/CNPJ:";
		document.getElementById("tr_CPF").style.visibility="visible";
		break;
	 case 172:
		document.getElementById("label_CPF").innerHTML="No. de Contribuinte:";
		document.getElementById("tr_CPF").style.visibility="visible";
		break;
	 default: 
		document.getElementById("tr_CPF").style.visibility="hidden";
	}
}

function VerificaNIBCPF(){
	
	cod = parseInt(document.getElementById("cad_pais").value);
	cpf = document.getElementById("cad_CPF_CNPJ").value;
	var ret;
	switch(cod){
	 case 30:
		ret = validaCPF(cpf);
		break;
	 case 172:
		ret = validaNIF(cpf);
		break;
	}
	
}

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_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_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];}
}


// AJAX

function abreAjax(){
    var ajax;        
    try{
    	ajax = new XMLHttpRequest();
    }
	catch(ee){
		try{
        	ajax = new ActiveXObject("Msxml2.XMLHTTP");
        }
		catch(e){
        	try{
            	ajax = new ActiveXObject("Microsoft.XMLHTTP");
            }
			catch(E){
            	ajax = false;
            }
		}
	}
    return ajax;
}

function xmlAjax(){
	var xmldoc;
	try{
    	xmldoc = new xmlDocument();
	}
	catch(eee){
    	try{
       		xmldoc = new ActiveXObject("Msxml2.DOMDocument");
    	}
		catch(eeee){
        	try{
            	xmldoc = new ActiveXObject("Microsoft.XMLDOM");
        	}
			catch(EE){
            	xmldoc = null;
        	}
    	}
	}
	return xmldoc;
}


function populaestados(pais,estado,cidade,espera){
	
	var ajax = abreAjax();
	var xmldoc = xmlAjax();
	var total1 = document.getElementById(estado).options.length;
	if(cidade !=''){
		var total2 = document.getElementById(cidade).options.length;
	}
	var i = 0;
	var j = 0;
	
	document.getElementById(espera).innerHTML  = "<font color=red>Aguarde...</font>";
	
	while (i < total1){
		document.getElementById(estado).remove(0);
		i++;
	}
	
	if(cidade !=''){
		while (j < total2){
			document.getElementById(cidade).remove(0);
			j++;
		}
	}
	
	ajax.open("GET","http://www.reciclecarbono.com.br/ajax/estados.php?est_pais=" + document.getElementById(pais).value,true);
	ajax.onreadystatechange = function() {
		
		var objmun;
		var ret;
	
		if (ajax.readyState == 4) {
			if (window.ActiveXObject){
				ret = xmldoc.loadXML(ajax.responseText);
				if (ret!=true){
					alert("No foi possvel ler o documento");
					document.body.style.cursor = "";
					document.getElementById(espera).innerHTML = "";
					return(0);
				}
				
				xmldoc.resolveExternals=false;
				xmldoc.async=false;
				
				var root = xmldoc.documentElement;
				
				var i = 0;
				while (i <= root.childNodes.length - 1){
						objest = document.createElement('Option');
						objest.text = root.childNodes.item(i).nodeTypedValue;
						objest.value = root.childNodes.item(i).attributes.getNamedItem('cd_estado').value;
						document.getElementById(estado).add(objest);
				
						i++;
				}
				document.body.style.cursor = "";
				document.getElementById(espera).innerHTML = "";
			}else{        
				var xmlParser = new DOMParser();
				xmldoc = xmlParser.parseFromString(ajax.responseText,"text/xml");
				xmldoc.resolveExternals=false;
				xmldoc.async=false;
				
				var root = xmldoc.documentElement;
				
				var i = 0;
				while (i <= root.childNodes.length - 1){
					if (root.childNodes.item(i).nodeName == 'ROW'){
						objest = document.createElement('Option');
						objest.text = root.childNodes.item(i).childNodes.item(0).nodeValue;
						objest.value = root.childNodes.item(i).attributes.getNamedItem('cd_estado').value;
						document.getElementById(estado).add(objest,null);
					}
					i++
				}
				document.body.style.cursor = "";
				document.getElementById(espera).innerHTML = "";
			}
		}	
	}
	ajax.send(null);
}

function populamunicipio(estado,cidade,espera){
	
	var ajax = abreAjax();
	var xmldoc = xmlAjax();
	var total = document.getElementById(cidade).options.length;
	var i = 0;
	
	document.getElementById(espera).innerHTML  = "<font color=red>Aguarde...</font>";
	
	while (i < total){
		document.getElementById(cidade).remove(0);
		i++;
	}

	ajax.open("GET","http://www.reciclecarbono.com.br/ajax/cidades.php?cid_estado=" + document.getElementById(estado).value,true);
	ajax.onreadystatechange = function() {
		
		var objmun;
		var ret;
	
		if (ajax.readyState == 4) {
			if (window.ActiveXObject){
				ret = xmldoc.loadXML(ajax.responseText);
				if (ret!=true){
					alert("No foi possvel ler o documento");
					document.body.style.cursor = "";
					document.getElementById("wait").innerHTML = "";
					return(0);
				}
				
				xmldoc.resolveExternals=false;
				xmldoc.async=false;
				
				var root = xmldoc.documentElement;
				
				var i = 0;
				while (i <= root.childNodes.length - 1){
						objmun = document.createElement('Option');
						objmun.text = root.childNodes.item(i).nodeTypedValue;
						objmun.value = root.childNodes.item(i).attributes.getNamedItem('cd_municipio').value;
						document.getElementById(cidade).add(objmun);
				
						i++;
				}
				document.body.style.cursor = "";
				document.getElementById(espera).innerHTML = "";
			}else{        
				var xmlParser = new DOMParser();
				xmldoc = xmlParser.parseFromString(ajax.responseText,"text/xml");
				xmldoc.resolveExternals=false;
				xmldoc.async=false;
				
				var root = xmldoc.documentElement;
				
				var i = 0;
				while (i <= root.childNodes.length - 1){
					if (root.childNodes.item(i).nodeName == 'ROW'){
						objmun = document.createElement('Option');
						objmun.text = root.childNodes.item(i).childNodes.item(0).nodeValue;
						objmun.value = root.childNodes.item(i).attributes.getNamedItem('cd_municipio').value;
						document.getElementById(cidade).add(objmun,null);
					}
					i++
				}
				document.body.style.cursor = "";
				document.getElementById(espera).innerHTML = "";
			}
		}	
	}
	ajax.send(null);
}
