// JavaScript Document
//mudar fundo de input


function inicia(combo){
	var campo = document.getElementById(combo);
local1 = new Array();
var maximo1, i, campo1;
local1 = myIframe.org;
campo1 = campo;
maximo1 = local1.length;
campo.options.length = 0;
//addItem(campo1,'TODAS','',false,campo1.length);
for (i=0;i<maximo1;i++){
  addItem(campo1,local1[i][1],local1[i][0],false,campo1.length);
}
}

function addItem(obj,strText,strValue,blSel,intPos){ 
    var newOpt,i,ArTemp,selIndex; 
    selIndex = (blSel)?intPos:obj.selectedIndex; 
    newOpt = new Option(strText,strValue); 
    Len = obj.options.length+1 
    if (intPos > Len) return 
    obj.options.length = Len 
    if (intPos != Len) { 
         ArTemp = new Array(); 
         for(i=intPos;i<obj.options.length-1;i++) 
              ArTemp[i] = Array(obj.options[i].text,obj.options[i].value); 
         for(i=intPos+1;i<Len;i++) 
              obj.options[i] = new Option(ArTemp[i-1][0],ArTemp[i-1][1]); 
    } 
    obj.options[intPos] = newOpt; 
    if (selIndex > intPos) 
         obj.selectedIndex = selIndex+1; 
    else if (selIndex == intPos)  
         obj.selectedIndex = intPos; 
} 

function mudaFundo(colorin,objeto,qtd){
	if(qtd==undefined){
		document.getElementById(objeto).className = colorin
	}else{
	for(i=1;i<=qtd;i++){
		cell=objeto+i
document.getElementById(cell).className = colorin
	}
	}
}

//centralizando a janela
function centraliza(x,y)
{
        window.resizeTo(x,y);
        window.moveTo((window.screen.width-x)/2,(window.screen.height-y)/2);
}

//abrindo uma popup
function AbrirPopup(url,nome,tipo){
if (tipo==1){
	metodo='scrollbars=no,resizable=no,menubar=no,location=no,status=no'
}else if (tipo==2){
	metodo='scrollbars=yes,resizable=yes,menubar=yes,location=yes,status=yes'
}else{
metodo='scrollbars=no,resizable=no,menubar=no,location=no,status=no'
}
window.open(url,nome,metodo)
}
//fixando a tela
function fixaTela(fixa){
document.location='#'+fixa
}

/*********funções automáticas do dreamweaver *********/
//mostra e oculta layers
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_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}
//colocando o texto no layer
function MM_setTextOfLayer(objName,x,newText) { //v4.01
  if ((obj=MM_findObj(objName))!=null) with (obj)
    if (document.layers) {document.write(unescape(newText)); document.close();}
    else innerHTML = unescape(newText);
}

//mensagem na barra de status
function MM_displayStatusMsg(msgStr) { //v1.0
  status=msgStr;
  document.MM_returnValue = true;
}

//imagem swaping
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_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_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];}
}

/******************************/
//ir para a página de produtos
function goProdutos(pagina,bot){
	if (pagina=='Parceiros'){
		carregaAjax('divPrinc','Parceiros.asp','get','');
	}else{
carregaAjax('divPrinc','Produtos.asp?seg='+pagina,'get','');
	}
	
	//mudando a cor
	for(i=1;i<=5;i++){
botao='bot'+i
if(i==bot){
document.getElementById(botao).src='images/home/home_bot_0'+i+'_azul.jpg'
document.getElementById('barrinha').src='images/home/barrinha_azul.jpg'
document.getElementById('cellBar').className='cellBarAzul'
}else{
	document.getElementById(botao).src='images/home/home_bot_0'+i+'.jpg'
}
	}
}

//validando auto atendimento
function validaAutoAtendimento(form){
	Formulario = document.getElementById(form)
if (Formulario.grupo.value == ""){
		//alert("Digite o Grupo.");
		Formulario.grupo.focus();
		return false;
	}
		if (Formulario.grupo.value.length <4){
		//alert("Digite 4 dígitos para Grupo.");
		Formulario.grupo.focus();
		Formulario.grupo.value = Formulario.grupo.value;
		return false;
	}
	if (Formulario.cota.value == ""){
		//alert("Digite a Cota.");
		Formulario.cota.focus();
		return false;
	}
	if (Formulario.cota.value.length <3){
		//alert("Digite 3 dígitos para Cota.");
		Formulario.cota.focus();
		Formulario.cota.value = Formulario.cota.value;
		return false;
	}
	if (Formulario.senha.value == ""){
		//alert("Digite a Senha.");
		Formulario.senha.focus();
		return false;
	}
	if (Formulario.senha.value.length <8){
		//alert("Digite 8 dígitos para Senha.");
		Formulario.senha.focus();
		Formulario.senha.value = Formulario.senha.value;
		return false;
	}
	
	document.location='webvenda.asp'
	return true
}
//direcionando URL
function direciona(url){
parent.document.location=url
}

function LoadingPage(Local,Page){
document[Local].location = Page	
}
//poe msg no status

//criando o objeto ajax
function openAjax() { 
var Ajax; 
try {Ajax = new XMLHttpRequest(); // XMLHttpRequest para browsers mais populares, como: Firefox, Safari, dentre outros. 
}catch(ee) { 
try {Ajax = new ActiveXObject("Msxml2.XMLHTTP"); // Para o IE da MS 
}catch(e) { 
try {Ajax = new ActiveXObject("Microsoft.XMLHTTP"); // Para o IE da MS 
}catch(e) {Ajax = false; 
} 
} 
} 
return Ajax; 
}

//evita o cache
    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());}
    }

//para executar script dentro de um arquivo carregado via ajax
function ExtraiScript(texto){
    var ini, pos_src, fim, codigo;
    var objScript = null;
    ini = texto.indexOf('<script', 0)
    while (ini!=-1){
        var objScript = document.createElement("script");
        //Busca se tem algum src a partir do inicio do script
        pos_src = texto.indexOf(' src', ini)
        ini = texto.indexOf('>', ini) + 1;

        //Verifica se este e um bloco de script ou include para um arquivo de scripts
        if (pos_src < ini && pos_src >=0){//Se encontrou um "src" dentro da tag script, esta e um include de um arquivo script
            //Marca como sendo o inicio do nome do arquivo para depois do src
            ini = pos_src + 4;
            //Procura pelo ponto do nome da extencao do arquivo e marca para depois dele
            fim = texto.indexOf('.', ini)+4;
            //Pega o nome do arquivo
            codigo = texto.substring(ini,fim);
            //Elimina do nome do arquivo os caracteres que possam ter sido pegos por engano
            codigo = codigo.replace("=","").replace(" ","").replace("\"","").replace("\"","").replace("\'","").replace("\'","").replace(">","");
            // Adiciona o arquivo de script ao objeto que sera adicionado ao documento
            objScript.src = codigo;
        }else{//Se nao encontrou um "src" dentro da tag script, esta e um bloco de codigo script
            // Procura o final do script
            fim = texto.indexOf('</script>', ini);
            // Extrai apenas o script
            codigo = texto.substring(ini,fim);
            // Adiciona o bloco de script ao objeto que sera adicionado ao documento
            objScript.text = codigo;
        }

        //Adiciona o script ao documento
        document.body.appendChild(objScript);
        // Procura a proxima tag de <script
        ini = texto.indexOf('<script', fim);

        //Limpa o objeto de script
        objScript = null;
    }
}

// carregando via ajax
function carregaAjax(id,pagina,metodo,idForm,fix,upload) {
if(document.getElementById) { // Para os browsers complacentes com o DOM W3C. 
var exibeResultado = document.getElementById(id); // div que exibirá o resultado. 
var Ajax = openAjax(); // Inicia o Ajax. 
if (pagina==''){
	exibeResultado.innerHTML = '<img height=0>'
	//caso contrario
}else{
pagina=antiCacheRand(pagina);
Ajax.open(metodo, pagina, true); // fazendo a requisição

if(idForm!=''){
if(metodo=='post'){
	if(upload==undefined){
Ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // enviadno o form
	}else{
	Ajax.setRequestHeader("Content-Type", "multipart/form-data");
	// enviadno o form	
	}
	setRequestHeader("Content-Type", "text/html; charset=iso-8859-1");
// valores
}
elementosForm = BuscaElementosForm(idForm)
}else{
elementosForm=null
}
Ajax.onreadystatechange = function() 
{ 
if(Ajax.readyState == 1) { // Quando estiver carregando, exibe: carregando... 
exibeResultado.innerHTML = "<div align=’center’ class='textoLaranja'><strong>Carregando...</strong></div>"; 
} 
if(Ajax.readyState == 4) { // Quando estiver tudo pronto. 
if((Ajax.status == 200)||(Ajax.status==0)) { 
var resultado = Ajax.responseText; // Coloca o retornado pelo Ajax nessa variável 
resultado = resultado.replace(/\+/g," "); // Resolve o problema dos acentos (saiba mais aqui: http://www.plugsites.net/leandro/?p=4) 
resultado = unescape(resultado); // Resolve o problema dos acentos 
exibeResultado.innerHTML = resultado;

ExtraiScript(resultado)
if(fix!=undefined){
fixaTela(fix)
}
} else if (Ajax.status==404){
exibeResultado.innerHTML = "<div align=’center’ class='textoLaranja'><font color=red><strong>Não foi possível encontrar a página!</font></strong></div>"; 
}else{
	exibeResultado.innerHTML = "<div align=’center’ class='textoLaranja'><font color=red><strong>Ocorreu algum erro!</font></strong></div>"; 
} 
} 
} 
Ajax.send(elementosForm); // submete 
} 
}
}

//função para buscar elementos form
function BuscaElementosForm(idForm) {
    var elementosFormulario = document.getElementById(idForm).elements;
    var qtdElementos = elementosFormulario.length;
    var queryString = "";
    var elemento;

    //Cria uma funcao interna para concatenar os elementos do form
    this.ConcatenaElemento = function(nome,valor) { 
                                if (queryString.length>0) { 
                                    queryString += "&";
                                }
                                queryString += encodeURIComponent(nome) + "=" + encodeURIComponent(valor);
                             };

    //Loop para percorrer todos os elementos
    for (var i=0; i<qtdElementos; i++) {
        //Pega o elemento
        elemento = elementosFormulario[i];
        if (!elemento.disabled) {
            //Trabalha com o elemento caso ele nao esteja desabilitado
            switch(elemento.type) {
                //Realiza a acao dependendo do tipo de elemento
                case 'text': case 'password': case 'hidden': case 'textarea': 
                    this.ConcatenaElemento(elemento.name,elemento.value);
                    break;
                case 'select-one':
                    if (elemento.selectedIndex>=0) {
                        this.ConcatenaElemento(elemento.name,elemento.options[elemento.selectedIndex].value);
                    }
                    break;
                case 'select-multiple':
                    for (var j=0; j<elemento.options.length; j++) {
                        if (elemento.options[j].selected) {
                            this.ConcatenaElemento(elemento.name,elemento.options[j].value);
                        }
                    }
                    break;
                case 'checkbox': case 'radio':
                    if (elemento.checked) {
                        this.ConcatenaElemento(elemento.name,elemento.value);
                    }
                    break;
            }
        }
    }
    return queryString;
}

/**nova funcção de busca*/
function carregaDados(Source,parameters){
var head = document.getElementsByTagName('head').item(0);
var eScript = document.createElement('script');
if(parameters!=undefined){
parameters='?'+parameters
}else{
parameters=''
}
var file=Source+parameters
file=antiCacheRand(file);
eScript.setAttribute('src',file);
head.appendChild(eScript)
}

//Meses
var NomeMes=new Array()
NomeMes[0]="Janeiro"
NomeMes[1]="Fevereiro"
NomeMes[2]="Març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"


//função de carregamento de cidades
function carregarCidades(page){
var url;
url = page+'?aux=1&cod_estado='+document.formulario.estado[document.formulario.estado.selectedIndex].value;
document.formulario.cidade.options.length = 0;
document.formulario.UF.value = document.formulario.estado[document.formulario.estado.selectedIndex].id;
if (document.formulario.estado.value=="Sem Estado"){
window.location.href='default.asp';
}else{
addItem(document.formulario.cidade,"Aguarde...carregando", "",false,document.formulario.cidade.length)
}
myIframe.location = url;
document.formulario.cidade.focus()
}

function verifyCidade(valor){
if(valor=='nenhum'){
document.formulario.estado.focus();	
}
}


function valida(){
var errMsg='';
var form=document.formAutoAtend;

if (form.grupo.value==""){
errMsg='Informe um grupo';
campo='grupo';
}

if(errMsg==''){
if (form.grupo.value.length<4){
 errMsg='Somente 4 dígitos para o grupo';
campo='grupo';
}
}

if(errMsg==''){
if (form.cota.value==''){
  errMsg='Informe uma cota';
  campo='cota';
}
}

if(errMsg==''){
if (form.cota.value.length<3){
  errMsg='Somente 3 dígitos para a cota';
 campo='cota';
}
}

if(errMsg==''){
if (form.senha.value==''){
  errMsg='Informe uma senha';
campo='senha';
}
}

if (errMsg!=''){
alert(errMsg)
form[campo].focus()
return false
}
return true
}


function verifyTam(tam,inputCamp,outputCamp){
	var tecla=window.event.keyCode;
	
    if (tecla!=8){
	if(inputCamp.value.length==tam){
		outputCamp.focus();
		
	}
	}
}