// REDIMENSIONA AS IMAGENS CASO SEJAM MAIORES QUE A LARGURA PERMITIDA DO SITE
// ----------------------------------------------------------------------------
window.onload = function() {
	RedimensionaImagens(600);
}

function RedimensionaImagens(tamanhoimg) {
  var obj = document.getElementsByTagName("div");
  for(var i = 0;i<obj.length;i++) {
    if (obj[i].className == "imgstyle") {
      var img = obj[i].getElementsByTagName("img");
      if (img[0].width > tamanhoimg) { obj[i].innerHTML = '<img src="' + img[0].src + '" width="'+ tamanhoimg +'">' + '<br><a href="' + img[0].src + '" target="_blank">Veja a imagem no tamanho original</a>'; }
    }
  }
}


// FUNÇÃO DE EXIBIÇÃO DE ARQUIVOS FLASH
// ----------------------------------------------------------------------------
function ExibeFlash(w,h,wmode,movie) {
	document.write('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="'+w+'" height="'+h+'">');
	document.write('<param name="wmode" value="'+wmode+'"/>');
	document.write('<param name="quality" value="high"/>');
	document.write('<param name="movie" value="'+movie+'"/>');
	document.write('<embed src="'+movie+'" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" wmode="'+wmode+'" width="'+w+'" height="'+h+'"></embed>');
	document.write('</object>');
}


//===============================================================================
//= ABRE POP-UP CENTRALIZADO ====================================================
//===============================================================================
var win = null;
function NewWindow(mypage,myname,w,h,scroll){
	LeftPosition = parseInt((screen.width) ? (screen.width-w)/2 : 0);
	TopPosition = parseInt((screen.height) ? (screen.height-h)/2 : 0);
	settings = 'width='+w+',height='+h+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',noresizable,status=yes'
	win = window.open(mypage,myname,settings)
}


//===============================================================================
//= REDIMENSIONA POP-UP =========================================================
//===============================================================================
function Redimensiona(w, h) {
	//Corrige o tamanho da janela
	if (navigator.appName == "Microsoft Internet Explorer") {
		w = parseInt(w) + 10;
		h = parseInt(h) + 48;
	} else {
		w = parseInt(w) + 6;
		h = parseInt(h) + 49;
	};
	// IE 7
	var nversao = navigator.appVersion;
	var nresult = nversao.search(/\bMSIE 7.0\b/g);
	if (nresult > 0) {
		h = parseInt(h) + 28;
	};
	//
	window.resizeTo(w, h);
	LeftPosition =  parseInt((screen.width) ? (screen.width-w)/2 : 0);
	TopPosition =  parseInt((screen.height) ? (screen.height-h)/2 : 0);
	window.moveTo(LeftPosition,TopPosition);
	window.focus();
}



// FUNÇÃO DE EXIBIÇÃO DE ARQUIVOS DE VÍDEO
// ----------------------------------------------------------------------------
function ExibeVideo(w,h,movie) {
            document.write('<object id="video" width="'+w+'" height="'+h+'" border="0" classid="CLSID:05589FA1-C356-11CE-BF01-00AA0055595A">');
            document.write('  <param name="ShowControls" value="1">');
            document.write('  <param name="AutoStart" value="1">');
				document.write('  <param name="ShowDisplay" value="0">');
            document.write('  <param name="AutoRewind" value="0">');
            document.write('  <param name="PlayCount" value="0">');
            document.write('  <param name="Appearance value="0">');
            document.write('  <param name="BorderStyle value="0">');
            document.write('  <param name="MovieWindowWidth" value="'+w+'">');
				document.write('  <param name="MovieWindowHeight" height="'+h+'">');
            document.write('  <param name="FileName" value="'+movie+'">');
            document.write('  <embed src="'+movie+'" type="video/x-msvideo" width="'+w+'" height="'+h+'" loop="true" autostart="true" controls="true"></embed>');
            document.write('</object>');
}

// FUNÇÃO DE EXIBIÇÃO DE TEXTO NA BARRA DE STATUS
// ----------------------------------------------------------------------------
function StatusBar(msgStr) { //v1.0
  status=msgStr;
  document.MM_returnValue = true;
}

function MM_displayStatusMsg(msgStr) { //v1.0
  status=msgStr;
  document.MM_returnValue = true;
}


function EscondeDicas(id) {
	document.getElementById(id).style.display = (document.getElementById(id).style.display == 'none') ? '' : 'none';
}

function EscondeProdutos(id) {
	document.getElementById(id).style.display = (document.getElementById(id).style.display == 'none') ? '' : 'none';
}


/* 
	Mascara para Campos.
	"#" - Numeros
	"A" - Letras UpperCase
	"a" - Letras LowerCase
	"Z" - Letras
	"*" - Qualquer Caracter
	"/", ".", "-", " ", ":" - Caracteres Fixos
*/
function Mascara(objeto, evt, mask) {
		
	var LetrasU = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	var LetrasL = 'abcdefghijklmnopqrstuvwxyz';
	var Letras 	= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
	var Numeros = '0123456789';
	var Fixos 	= '().-:/ '; 
	var Charset = " !\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_/`abcdefghijklmnopqrstuvwxyz{|}~";
	
	evt = (evt) ? evt : (window.event) ? window.event : "";
	var value = objeto.value;
	if (evt) {
		var ntecla = (evt.which) ? evt.which : evt.keyCode;
		tecla = Charset.substr(ntecla - 32, 1);
		if (ntecla < 32) return true;

		var tamanho = value.length;
		if (tamanho >= mask.length) return false;

		var pos = mask.substr(tamanho,1); 
		while (Fixos.indexOf(pos) != -1) {
			value += pos;
			tamanho = value.length;
			if (tamanho >= mask.length) return false;
			pos = mask.substr(tamanho,1);
		}

		switch (pos) {
				case '#' : if (Numeros.indexOf(tecla) == -1) return false; break;
				case 'A' : if (LetrasU.indexOf(tecla) == -1) return false; break;
				case 'a' : if (LetrasL.indexOf(tecla) == -1) return false; break;
				case 'Z' : if (Letras.indexOf(tecla) == -1) return false; break;
				case '*' : objeto.value = value; return true; break;
				default : return false; break;
		}
	}
	objeto.value = value; 
	return true;
}

// Deixa a string apenas com os numeros, eliminando o restante.
function trimToDigits(string) {
	s = "";
	var Numeros = /\d/;
	for (i = 0; i <= string.length; i++) 
		if (Numeros.test(string.substr(i,1))) s += string.substr(i,1);
	return s;	
}

function VEmail( strEmail ) {
     var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
     return (filter.test(strEmail));
}

function VAno(ano) {
	ano = trimToDigits(ano);
	return ((parseInt(ano) < 1900) || (ano.length != 4) || (parseInt(ano) > 2050)) ? false : true; 
}

function VMes(mes) {
	mes = trimToDigits(mes);
	return ((mes.length != 2) || (parseInt(mes) < 1) || (parseInt(mes) > 12)) ? false : true; 
}

function VMesAno(data) {
	data = trimToDigits(data);
	if (data.length < 6) return false;
	mes = data.substr(0,2);
	ano = data.substr(2,4);
	return (!VAno(ano) || !VMes(mes)) ? false : true;
}
//Verifica se a data é valida
function VData(data) {
	data = trimToDigits(data);
	if (data.length < 8) return false;
	dia = data.substr(0,2);
	mes = data.substr(2,2);
	ano = data.substr(4,4);
	
	if(ano >= 0 && ano < 1900) return false; 
	if(ano > 2100 || ano < 0 || mes > 12 || mes < 1) return false; 
	numero = ((parseInt(ano) - 1884) / 4) 
	dias = (numero == Math.floor(numero)) ? "312931303130313130313031" : "312831303130313130313031"; 
	diamax = parseInt(dias.substring((mes - 1) * 2, ((mes - 1) * 2) + 2)); 
	if(dia < 1 || dia > diamax) return false; 	
	
	return true;
}

// Verifica a autenticidade do CPF
function VCPF(cpf) {
	cpf = trimToDigits(cpf);
	if (cpf.length < 11) return false;
	valor = true;
	if (cpf == "00000000000" || cpf == "11111111111" || 
			cpf == "22222222222" || cpf == "33333333333" || 
			cpf == "44444444444" || cpf == "55555555555" || 
			cpf == "66666666666" || cpf == "77777777777" || 
			cpf == "88888888888" || cpf == "99999999999") return false;

	var a = [];
	var b = new Number;
	var c = 11;
	for (i = 0; i < 11; i++) {
		a[i] = cpf.charAt(i);
		b = (i < 9) ? b + (a[i] *  --c) : b;
	}
	
	a[9] = ((x = b % 11) < 2) ? 0 : 11 - x;

	b = 0;
	c = 11;
	for (y = 0; y < 10; y++) b += (a[y] *  c--); 
	a[10] = ((x = b % 11) < 2) ? 0 : 11 - x;

	return (cpf.charAt(9) == a[9]) && (cpf.charAt(10) == a[10]);
}	

function VCNPJ(cnpj) {
	cnpj = trimToDigits(cnpj);
	if (cnpj.length < 14) return false;
	m2 = 2;		
	soma1 = 0;
	soma2 = 0;
	for ( i = 11; i >= 0; i--) {
		val = eval(cnpj.charAt(i));
		m1 = m2;
		if (m2 < 9) { m2++ }
	 	else { m2 = 2 }
		soma1 = soma1 + (val * m1)
		soma2 = soma2 + (val * m2)
  }
	soma1 = soma1 % 11
	if (soma1 < 2) { d1 = 0 }
  else { d1 = 11 - soma1}
	soma2 = (soma2 + (2 * d1)) % 11
	if (soma2 < 2) { d2 = 0 }
  else { d2 = 11 - soma2}
	return (cnpj.charAt(12) == d1) && (cnpj.charAt(13) == d2);
}

function MaskAno(objeto, evt) { 
	return Mascara(objeto, evt, '####');
}

function MaskMesAno(objeto, evt) { 
	return Mascara(objeto, evt, '##/####');
}

function MaskCEP(objeto, evt) { 
	return Mascara(objeto, evt, '##.###-###');
}

function MaskTelefone(objeto, evt) { 
	return Mascara(objeto, evt, '(##) ####-####');
}

function MaskCPF(objeto, evt) { 
	return Mascara(objeto, evt, '###.###.###-##');
}

function MaskCNPJ(objeto, evt) { 
	return Mascara(objeto, evt, '##.###.###/####-##');
}

function MaskData(objeto, evt) { 
	return Mascara(objeto, evt, '##/##/####');
}

function MaskHora(objeto, evt) { 
	return Mascara(objeto, evt, '##:##');
}

function MaskHora2(objeto, evt) { 
	return Mascara(objeto, evt, '##:##:##');
}

var tipo = 0;

function FaleConosco() {
	tipo = 1;
	document.form1.action = "mail.asp";
	document.form1.method = "post";
}

function Newsletter() {
	tipo = 2;
	document.form1.action = "newsletter-action.asp";
	document.form1.method = "post";
}

function Busca() {
	tipo = 3;
	document.form1.action = "";
	document.form1.method = "get";
}

function AcessoRestrito() {
	tipo = 4;
	document.form1.action = "../acessorestrito/login.asp";
	document.form1.method = "post";
}

function AlterarSenha() {
	tipo = 5;
	document.form1.action = "../acessorestrito/alterar-action.asp";
	document.form1.method = "post";
}

function VFaleConosco() {
	if (!document.form1.nome.value) { alert("Por favor, informe seu nome."); document.form1.nome.focus(); return false; };
  if (!VEmail( document.form1.email.value)) { alert("O seu e-mail não é válido!\nVerifique-o novamente."); document.form1.email.focus(); return false; };
  if (!document.form1.telefone.value) { alert("Por favor, informe o telefone."); document.form1.telefone.focus(); return false; };
  if (!document.form1.cidade.value) { alert("Por favor, informe a cidade."); document.form1.cidade.focus(); return false; };
  if (!document.form1.mensagem.value) { alert("Você deve escrever a mensagem."); document.form1.mensagem.focus(); return false; };
  return true;
}

function VNewsletter() {
	if (!document.form1.newsnome.value) { alert("Por favor, informe seu nome."); document.form1.newsnome.focus(); return false; };
  if (!VEmail(document.form1.newsemail.value)) { alert("O seu e-mail não é válido!\nVerifique-o novamente."); document.form1.newsemail.focus(); return false; };
  return true;
}

function VBusca() {
	if (!(document.form1.busca.value.length > 1)) { alert("Informe um número maior de caracteres para busca."); document.form1.busca.focus(); return false; };
	return true;
}

function VAcessoRestrito() {
  if (document.form1.login.value == "") { alert("Por favor, informe seu Login."); document.form1.login.focus(); return false; };
  if (document.form1.senha.value == "") { alert("Por favor, informe a Senha."); document.form1.senha.focus(); return false; };
  return true;
}

function VAlterarSenha() {
  if (document.form1.asenha.value == "") { alert("Por favor, informe a Senha atual."); document.form1.asenha.focus(); return false; };
  if (document.form1.nsenha.value == "") { alert("Por favor, informe a nova Senha."); document.form1.nsenha.focus(); return false; };
  if (document.form1.csenha.value == "") { alert("Por favor, confirme a sua nova Senha."); document.form1.csenha.focus(); return false; };
  if (document.form1.nsenha.value != document.form1.csenha.value) { alert("As Senhas digitadas não coincidem."); document.form1.nsenha.focus(); return false; };
  return true;
}


function EnviaFormulario() {
	switch(tipo) {
		case 1: return VFaleConosco(); break;
		case 2: return VNewsletter(); break;
		case 3:	if (VBusca()) { document.location.href="busca.asp?busca=" + document.form1.busca.value; } break;
		case 4: return VAcessoRestrito();
		case 5: return VAlterarSenha();
	}
	return false;
}


function ajaxGet(url,elemento_retorno,exibe_carregando){
/******
* ajaxGet - Coloca o retorno de uma url em um elemento qualquer
* Use a vontade mas coloque meu nome nos créditos. Dúvidas, me mande um email.
* A função é grande, coloque-a em um arquivo .js separado.
* Versão: 1.2 - 20/04/2006
* Autor: Micox - Náiron J.C.G - micoxjcg@yahoo.com.br - elmicox.blogspot.com
* Parametros:
* url: string; elemento_retorno: object||string; exibe_carregando:boolean
*  - Se elemento_retorno for um elemento html (inclusive inputs e selects),
*    exibe o retorno no innerHTML / value / options do elemento
*  - Se elemento_retorno for o nome de uma variavel
*    (o nome da variável deve ser declarado por string, pois será feito um eval)
*    a função irá atribuir o retorno à variável ao receber a url.
*******/
    var ajax1 = pegaAjax();
    if(ajax1){
        url = antiCacheRand(url)
        ajax1.onreadystatechange = ajaxOnReady
        ajax1.open("GET", url ,true);
        //ajax1.setRequestHeader("Content-Type", "text/html; charset=iso-8859-1");//"application/x-www-form-urlencoded");
        ajax1.setRequestHeader("Cache-Control", "no-cache");
        ajax1.setRequestHeader("Pragma", "no-cache");
        if(exibe_carregando){ put("Carregando ...")    }
        ajax1.send(null)
        return true;
    }else{
        return false;
    }
    function ajaxOnReady(){
        if (ajax1.readyState==4){
            if(ajax1.status == 200){
                var texto=ajax1.responseText;
                if(texto.indexOf(" ")<0) texto=texto.replace(/\+/g," ");
                //texto=unescape(texto); //descomente esta linha se tiver usado o urlencode no php ou asp
                put(texto);
                extraiScript(texto);
            }else{
                if(exibe_carregando){put("Falha no carregamento. " + httpStatus(ajax1.status));}
            }
            ajax1 = null
        }else if(exibe_carregando){//para mudar o status de cada carregando
                put("Carregando ..." )
        }
    }
    function put(valor){ //coloca o valor na variavel/elemento de retorno
        if((typeof(elemento_retorno)).toLowerCase()=="string"){ //se for o nome da string
            if(valor!="Falha no carregamento"){
                eval(elemento_retorno + '= unescape("' + escape(valor) + '")')
            }
        }else if(elemento_retorno.tagName.toLowerCase()=="input"){
            valor = escape(valor).replace(/\%0D\%0A/g,"")
            elemento_retorno.value = unescape(valor);
        }else if(elemento_retorno.tagName.toLowerCase()=="select"){        
            select_innerHTML(elemento_retorno,valor)
        }else if(elemento_retorno.tagName){
            elemento_retorno.innerHTML = valor;
            //alert(elemento_retorno.innerHTML)
        }    
    }
    function pegaAjax(){ //instancia um novo xmlhttprequest
        //baseado na getXMLHttpObj que possui muitas cópias na net e eu nao sei quem é o autor original
        if(typeof(XMLHttpRequest)!='undefined'){return new XMLHttpRequest();}
        var axO=['Microsoft.XMLHTTP','Msxml2.XMLHTTP','Msxml2.XMLHTTP.6.0','Msxml2.XMLHTTP.4.0','Msxml2.XMLHTTP.3.0'];
        for(var i=0;i<axO.length;i++){ try{ return new ActiveXObject(axO[i]);}catch(e){} }
        return null;
    }
    function httpStatus(stat){ //retorna o texto do erro http
        switch(stat){
            case 0: return "Erro desconhecido de javascript";
            case 400: return "400: Solicitação incompreensível"; break;
            case 403: case 404: return "404: Não foi encontrada a URL solicitada"; break;
            case 405: return "405: O servidor não suporta o método solicitado"; break;
            case 500: return "500: Erro desconhecido de natureza do servidor"; break;
            case 503: return "503: Capacidade máxima do servidor alcançada"; break;
            default: return "Erro " + stat + ". Mais informações em http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html"; break;
        }
    }
    function antiCacheRand(aurl){
        var dt = new Date();
        if(aurl.indexOf("?")>=0){// já tem parametros
            return aurl + "&" + encodeURI(Math.random() + "_" + dt.getTime());
        }else{ return aurl + "?" + encodeURI(Math.random() + "_" + dt.getTime());}
    }
}
function select_innerHTML(objeto,innerHTML){
/******
* select_innerHTML - altera o innerHTML de um select independente se é FF ou IE
* Corrige o problema de não ser possível usar o innerHTML no IE corretamente
* Veja o problema em: http://support.microsoft.com/default.aspx?scid=kb;en-us;276228
* Use a vontade mas coloque meu nome nos créditos. Dúvidas, me mande um email.
* Versão: 1.0 - 06/04/2006
* Autor: Micox - Náiron J.C.G - micoxjcg@yahoo.com.br - elmicox.blogspot.com
* Parametros:
* objeto(tipo object): o select a ser alterado
* innerHTML(tipo string): o novo valor do innerHTML
*******/
    objeto.innerHTML = ""
    var selTemp = document.createElement("micoxselect")
    var opt;
    selTemp.id="micoxselect1"
    document.body.appendChild(selTemp)
    selTemp = document.getElementById("micoxselect1")
    selTemp.style.display="none"
    if(innerHTML.toLowerCase().indexOf("<option")<0){//se não é option eu converto
        innerHTML = "<option>" + innerHTML + "</option>"
    }
    innerHTML = innerHTML.replace(/<option/g,"<span").replace(/<\/option/g,"</span")
    selTemp.innerHTML = innerHTML
    for(var i=0;i<selTemp.childNodes.length;i++){
        if(selTemp.childNodes[i].tagName){
            opt = document.createElement("OPTION")
            for(var j=0;j<selTemp.childNodes[i].attributes.length;j++){
                opt.setAttributeNode(selTemp.childNodes[i].attributes[j].cloneNode(true))
            }
            opt.value = selTemp.childNodes[i].getAttribute("value")
            opt.text = selTemp.childNodes[i].innerHTML
            if(document.all){ //IEca
                objeto.add(opt)
            }else{
                objeto.appendChild(opt)
            }                    
        }    
    }
    document.body.removeChild(selTemp)
    selTemp = null
}

function extraiScript(texto){
//Maravilhosa função feita pelo SkyWalker.TO do imasters/forum
//http://forum.imasters.com.br/index.php?showtopic=165277&
    // inicializa o inicio ><
    var ini = 0;
    // loop enquanto achar um script
    while (ini!=-1){
        // procura uma tag de script
        ini = texto.indexOf('<script', ini);
        // se encontrar
        if (ini >=0){
            // define o inicio para depois do fechamento dessa tag
            ini = texto.indexOf('>', ini) + 1;
            // procura o final do script
            var fim = texto.indexOf('</script>', ini);
            // extrai apenas o script
            codigo = texto.substring(ini,fim);
            // executa o script
            //eval(codigo);
            /**********************
            * Alterado por Micox - micoxjcg@yahoo.com.br
            * Alterei pois com o eval não executava funções.
            ***********************/
            novo = document.createElement("script")
            novo.text = codigo;
            document.body.appendChild(novo);
        }
    }
}

function LoadParceiros(estado) {
	var url = 'ondecomprar.asp?uf='+estado;
	
//	LoadAjax("get", url, send, 'locais');
	ajaxGet(url,document.getElementById('locais'),false);
}