// Função para enviar o formúlário frmLoja para o cgi-bin/lojaLJ.pl.

function Loja(acao, prod_id, dep, secao, outros){

    if(acao)   window.document.frmLoja.acao.value = acao;

    if(prod_id) {
        var found = window.document.frmLoja.prod_id.value.match('-');
        if ((acao == 'PE') && (found)) {
            window.document.frmLoja.prod_id.value += prod_id;
        } else {
            window.document.frmLoja.prod_id.value = prod_id;
        }
    }
    if(dep) {
        var found = window.document.frmLoja.dep.value.match('-');
        if ((acao == 'PE') && (found)) {
            window.document.frmLoja.dep.value += dep;
        } else {
            window.document.frmLoja.dep.value = dep;
        }
    }
    if(secao) {
        var found = window.document.frmLoja.secao.value.match('-');
        if ((acao == 'PE') && (found)) {
            window.document.frmLoja.secao.value += secao;
        } else {
            window.document.frmLoja.secao.value = secao;
        }
    }
    if(outros) {
        var campoNomeValor = new Array(), conteudoNomeValor = new Array(2);
        campoNomeValor = outros.split('|');

        for(var i = 0; i < campoNomeValor.length; i++) {
            conteudoNomeValor = campoNomeValor[i].split('=');
            if (conteudoNomeValor[0] == 'variacao') {
                if ((acao == 'PE') && (window.document.frmLoja.variacao.value != '')) {
                    window.document.frmLoja.variacao.value += conteudoNomeValor[1];
                } else {
                    window.document.frmLoja.variacao.value = conteudoNomeValor[1];
                }
            }else if(conteudoNomeValor[0] == 'pagina'){
				window.document.frmLoja[conteudoNomeValor[0]].value = conteudoNomeValor[1];
				document.frmLoja.pagHadassa.value = 1;
			}
			else {
                if(window.document.frmLoja[conteudoNomeValor[0]]) {
                    window.document.frmLoja[conteudoNomeValor[0]].value = conteudoNomeValor[1];
                }
            }
        }
    }
    if (acao == 'IMPRIMIR_PAGINA') {
        //Retornei ao target antigo no programa mt_imp_pag.pl
        document.frmLoja.target="topFrame1";
    }
	
    document.frmLoja.submit();
}

// Função para troca de imagens (botões)
function t(i) { 
    if (document.images) {
        x = i.split("-");
        if (! x[3]) {
            x[3] = '';
        }
        if(x[2] == 'g') {
            document[x[0] + x[3]].src = "../imagens/" + x[0] + x[1] + ".gif";
        } else {
            document[x[0] + x[3]].src = "../imagens/" + x[0] + x[1] + ".jpg";
        }
    }
}

// Submeter pedido para loja segura
function SubmeterPedido(acao) {
    var http = getHTTPObject(); // We create the HTTP Object

    //passar a lista do frmLoja para o formPedido
    if (document.getElementById('campobonus'))
    {
        var valor = document.getElementById('campobonus').value;
        if (valor == '') valor = 'zerabonus';
    }

    if (acao != 'PE') {
        var msg_erro=''; var ver_cep=''; var cep=''; var ver_email=''; var email=''; var ver_senha=''; var senha='';

        // Verificar se escolher forma de pagamento
        var marcou = 0;
        if (document.formPedido.formas) {
            for(var x=0;x<document.formPedido.formas.length;x++) {
                if (document.formPedido.formas[x].checked == true) {
                    marcou = 1;
                }
            }
        }
        if (marcou == 0) {
            if (document.formPedido.formas.checked == true) { marcou = 1; }
            if (marcou == 0) {
                msg_erro = '- Escolha uma Forma de Pagamento\n';
            }
        }

        // Para clientes não cadastrados, verificar se preencheu e-mail e CEP
        //if (document.formPedido.tipo_cad[0].checked == true) {
        if (acao == 'FIN') {

            if (document.formPedido.email2) {
                ver_email = document.formPedido.email2.value
                for (idx=0;idx<ver_email.length;idx++) {
                    if (ver_email.charAt(idx) == " ") { email = email + "" }
                    else { email = email + ver_email.charAt(idx); }
                }
            }

            if (email == '') {
                msg_erro += '- Informe seu e-mail (Cliente não cadastrado)\n';
            }

            // Verificar se carrinho tem localidade Brasil/Exterior, se tiver e estiver marcado exterior, verificar se escolheu país
            if ((document.formPedido.local_nao_cad) && (document.formPedido.local_nao_cad[1].checked == true)) {
                if (document.formPedido.paises_nao_cad) {
                    if (document.formPedido.paises_nao_cad.selectedIndex == 0) {
                        msg_erro += '- Escolha o país de entrega do pedido (Cliente não cadastrado)\n';
                    }
                }
            } else {
                if (document.formPedido.cep3) {
                    ver_cep = document.formPedido.cep3.value
                    for (idx=0;idx<ver_cep.length;idx++) {
                        if (ver_cep.charAt(idx) == " ") { cep = cep + "" }
                        else { cep = cep + ver_cep.charAt(idx); }
                    }

                    if ((cep == '') && (document.formPedido.cep)) {
                        ver_cep = document.formPedido.cep.value
                        for (idx=0;idx<ver_cep.length;idx++) {
                            if (ver_cep.charAt(idx) == " ") { cep = cep + "" }
                            else { cep = cep + ver_cep.charAt(idx); }
                        }
                    }

                    // Verificar se o template tem o campo "Retirar produto na loja"
                    if (document.formPedido.retirar_loja1) {
                        // Se o campo não estiver marcado e o CEP não preenchido, acusar erro.
                        if (document.formPedido.retirar_loja1.checked == false) {
                            if (cep == '') {
                                msg_erro += '- Informe o CEP do local de entrega (Cliente não cadastrado)\n';
                            }
                        }
                    } else {
                        if (cep == '') {
                            msg_erro += '- Informe o CEP do local de entrega (Cliente não cadastrado)\n';
                        }
                    }
                }
            }
        }

        // Para clientes cadastrados, verificar se preencheu e-mail e senha
        //if (document.formPedido.tipo_cad[1].checked == true) {
        if (acao == 'FI') {

            if (document.formPedido.email) {
                ver_email = document.formPedido.email.value
                for (idx=0;idx<ver_email.length;idx++) {
                    if (ver_email.charAt(idx) == " ") { email = email + "" }
                    else { email = email + ver_email.charAt(idx); }
                }

                if (email == '') {
                    msg_erro += '- Informe seu e-mail (Cliente cadastrado)\n';
                }
            }


            if (document.formPedido.senha) {
				
				if(!document.getElementById('vendedor_id')){
					
					ver_senha = document.formPedido.senha.value
					for (idx=0;idx<ver_senha.length;idx++) {
						if (ver_senha.charAt(idx) == " ") { senha = senha + "" }
						else { senha = senha + ver_senha.charAt(idx); }
					}

					if (senha == '') {
						msg_erro += '- Informe sua senha (Cliente cadastrado)\n';
					}
				} else if ((document.getElementById('vendedor_id')) && (!document.getElementById('vendedor_id').value)) {
					
						ver_senha = document.formPedido.senha.value
						for (idx=0;idx<ver_senha.length;idx++) {
							if (ver_senha.charAt(idx) == " ") { senha = senha + "" }
							else { senha = senha + ver_senha.charAt(idx); }
						}

						if (senha == '') {
							msg_erro += '- Informe sua senha (Cliente cadastrado)\n';
						}
					}
            }

            if (document.formPedido.cep2) {
                ver_cep = document.formPedido.cep2.value
                for (idx=0;idx<ver_cep.length;idx++) {
                    if (ver_cep.charAt(idx) == " ") { cep = cep + "" }
                    else { cep = cep + ver_cep.charAt(idx); }
                }

                if ((cep == '') && (document.formPedido.cep)) {
                    ver_cep = document.formPedido.cep.value
                    for (idx=0;idx<ver_cep.length;idx++) {
                        if (ver_cep.charAt(idx) == " ") { cep = cep + "" }
                        else { cep = cep + ver_cep.charAt(idx); }
                    }
                }
            }
        }

        if (cep != '') {
            // cep possui apenas digito
            re0 = /^[\d]+$/;
            cep = cep.replace(/[\D]/gm,'');

            if (!re0.test(cep)){
                msg_erro += '- O CEP do local de entrega é inválido\n';
                msg_erro = 'Verifique o(s) iten(s) abaixo:\n' + msg_erro;
                alert(msg_erro);
            } else {
                var url = "./cep.pl?cep="; // The server-side script
                http.open("GET", url + escape(cep), true);
                http.onreadystatechange = handleHttpResponse;
                http.send(null);
            }
        } else {
            if (msg_erro != '') {
                msg_erro = 'Verifique o(s) iten(s) abaixo:\n' + msg_erro;
                alert(msg_erro);
            } else {

                if (acao == 'FI') {
                    if (document.formPedido.cep3) { document.formPedido.cep3.value = ''; }
                    document.formPedido.email2.value = '';
                } else {
                    if (document.formPedido.cep2) { document.formPedido.cep2.value = ''; }
                    document.formPedido.email.value = '';
                }

                document.formPedido.target='_top';
                document.formPedido.pedido.value = document.frmLoja.pedido.value;
                document.formPedido.loja.value = document.frmLoja.loja.value;
                document.formPedido.teste.value = document.frmLoja.teste.value;
                document.formPedido.acao.value = 'FI';
                document.formPedido.submit();
            }
        }

    } else {
			//if (document.frmLoja.loja.value == 213)
			//{
			//	alert('tim');
			//}
        document.formPedido.pedido.value = document.frmLoja.pedido.value;
        document.formPedido.loja.value = document.frmLoja.loja.value;
        document.formPedido.teste.value = document.frmLoja.teste.value;
        document.formPedido.acao.value = acao;
        document.formPedido.submit();
    }

    function handleHttpResponse() {
        if (http.readyState == 4) {

            // Split the comma delimited response into an array
            results = http.responseText.split("|");

            if (results[0] == 0) {
                msg_erro += '- O CEP do local de entrega é inválido\n';
            }

            if (msg_erro != '') {
                msg_erro = 'Verifique o(s) iten(s) abaixo:\n' + msg_erro;
                alert(msg_erro);
            } else {

                if (acao == 'FI') {
                    if (document.formPedido.cep3) { document.formPedido.cep3.value = ''; }
                    document.formPedido.email2.value = '';
                } else {
                    if (document.formPedido.cep2) { document.formPedido.cep2.value = ''; }
                    document.formPedido.email.value = '';
                }

                document.formPedido.target='_top';
                document.formPedido.pedido.value = document.frmLoja.pedido.value;
                document.formPedido.loja.value = document.frmLoja.loja.value;
                document.formPedido.teste.value = document.frmLoja.teste.value;
                document.formPedido.acao.value = 'FI';
                document.formPedido.submit();
            }
        }
    }
}

function getHTTPObject() {

    var xmlhttp;

    /*@cc_on
    @if (@_jscript_version >= 5)
        try {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
        try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (E) {
            xmlhttp = false;
        }
        }
    @else
    xmlhttp = false;
    @end @*/

    if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
        try {
        xmlhttp = new XMLHttpRequest();
        } catch (e) {
        xmlhttp = false;
        }
    }

    return xmlhttp;
}


//Chamar programa de esqueci senha
function EsqueciSenha(idioma,email) {

    var pedido;

    if ((!email) && (document.formPedido)) email = document.formPedido.email.value;
    if (document.formPedido) pedido = document.formPedido.pedido.value;

    if (email == "") {
        if (idioma == 'I') {
            alert('Enter your e-mail to sent the password hint.');
        } else {
            alert('Preencha o seu e-mail para ser enviada a dica da senha.');
        }
    } else {
        esqsenha = window.open('', 'esqsenha', 'menubar=no,toolbar=no,status=no,directories=no,location=no,scrollbars=0,resizable=no,width=300,height=150,top=1,left=1');
        esqsenha.window.location = 'loja.pl?acao=ESQSENHA&loja=' + document.frmLoja.loja.value + '&pedido=' + pedido + '&email=' + email;
    }
}


function MM_findObj(n, d) { //v4.0
  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 && document.getElementById) x=document.getElementById(n); return x;
}


function SH() { //v3.0
    var i,v,obj,args=SH.arguments;
    for (i=0; i<=(args.length-2); i+=2)
    if (document.getElementById(args[0]).innerHTML!=''){
        if ((obj=MM_findObj(args[i]))!=null) {
            v=args[i+1];
            (v == 'h')?(v = "hide"):(v = "show");
            if (obj.style) {
                obj=obj.style; v=(v=='show')?'visible':(v='hide')?'hidden':v;
            }
            obj.visibility=v;
        }
    }
}

//function enviaMala(){
//    var pas;
//
//    if (frmMala.opcao[0].checked == true){
//        pas = 'passo=entrar|loja='+frmMala.loja.value+'|pedido='+frmMala.pedido.value+'|teste=' +frmMala.teste.value+'|email='+frmMala.email.value;
//    } else { pas = 'passo=sair|loja='+frmMala.loja.value+'|pedido='+frmMala.pedido.value+'|teste=' +frmMala.teste.value+'|email='+frmMala.email.value; }
//
//    Loja('VERCAD','','','',pas);
//
//    return;
//}

function enviaMala()
{
	var passo;
	var opcao = 0;
	for (i=0;i<document.formMala.elements.length;i++)
	{
		if (document.formMala[i].name=='opcao')
		{
			opcao=1;
		}
	}

	if (opcao)
	{
		if (document.formMala.opcao.type == 'hidden')
		{
			passo = document.formMala.opcao.value;
		}
		else
		{
			for (var x=0;x<document.formMala.opcao.length;x++)
			{
				if (document.formMala.opcao[x].checked == true)
				{
					passo = document.formMala.opcao[x].value;
				}
			}
		}
	}
	else
	{
		passo = 'entrar';
	}

	if (!ValidaEmail(document.formMala.email.value))
	{
		alert("Digite um e-mail válido para se cadastrar");
		document.formMala.email.focus();
	}
	else
	{
		document.formMala.passo.value = passo;
		document.formMala.submit();
	}
}

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();
}
MM_reloadPage(true);

function AmpliarFoto(imagem,largura,altura){
    
    if (imagem == '') {
    	return;
    }
    
    if (largura == 0 || altura == 0) {
	oScript = document.createElement('script');
	oScript.src = 'js/ajax.js';
	oScript.type = 'text/javascript';
	document.body.appendChild(oScript);

	var http = criaHTTPObject();
	var parametros = new Array();
	parametros['img'] = imagem;
	var programa = 'http://'+document.domain+'/cgi-bin/ajxTamanhoImg.pl';
	chamaProcedimentoRemoto(http,programa,parametros,'TamImg','');
   } else {
	    var ampliar;
	    if ((largura >=500) || (altura >=500)) {
		if (largura > altura) {
		    altura = altura * (500 / largura);
		    largura = 500;
		} else if (altura > largura) {
		    largura = largura * (500 / altura);
		    altura = 500;
		} else {
		    largura = 500;
		    altura = 500;
		}
	    }

	    ampliar = window.open('','ampliar','menubar=no,toolbar=no,status=no,directories=no,location=no,scrollbars=1,resizable=yes,width='+largura+',height='+altura+',top=20,left=20');
	    ampliar.focus();
	    ampliar.document.open("text/html");
	    ampliar.document.write('<html><head><title>Imagem Ampliada</title></head><body bgcolor="#FFFFFF" text="#000000" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" scroll="auto"><a href="javascript:window.close();"><img src="'+imagem+'" width="'+largura+'" height="'+altura+'" border="0" alt="Clique na imagem para fechar a janela"></a></body></html>');
    }

}

function TamImg(tam) {
    dados = tam.split(',');
    AmpliarFoto(dados[0],dados[1],dados[2]);
}


// Função para Abrir Pop-up
function AbrirPopUp(url,loja_dir,popup_id,popup_width,popup_height) {
    loja_dir = loja_dir.replace(/0/gm,'');
    popup_id = popup_id.replace(/^0/,'');
    popup_id = popup_id.replace(/^0/,'');

    if (popup_id > 0) {

        popup_shop=window.open(url+'/'+loja_dir+'/paginas/popup'+popup_id+'.html','popup_shop','menubar=no,toolbar=no,status=no,directories=no,location=no,scrollbars=1,resizable=yes,width='+popup_width+',height='+popup_height+',top=20,left=50');
//        popup_shop.window.focus();

        if (window.ver_detalhe) {
            var largura = window.ver_detalhe.screen.width;
            var altura = window.ver_detalhe.screen.height;

            var janWidth; var janHeight;

            if (navigator.appName == 'Netscape') {
                janWidth = parseInt(popup_width) + 0;
                janHeight = parseInt(popup_height);
            }
            else {
                janWidth = parseInt(popup_width) + 6;
                janHeight = parseInt(popup_height) + 25;
            }

            if (janHeight > altura-20) {
                janHeight = altura-30;
            }

            popup_shop.self.resizeTo(janWidth,janHeight);
        }
    }
}

// Mostrar valor da embalagem de presente
function VerEmbalagem() {
    var linha_total = document.getElementById('LinhaTotal');
    if (document.formPedido.emb_presente.checked) {
        valor_embalagem.style.display = 'inline';
        linha_total.innerHTML = total_com_emb;
    } else {
        valor_embalagem.style.display = 'none';
        linha_total.innerHTML = total_normal;
    }
}


// Tirar produto do carrinho
function ValorZero(codigo) {
    for(var x=0;x<document.formPedido.elements.length;x++){
        if (document.formPedido.elements[x].name.substring(3) == codigo) {
			document.formPedido.elements[x].value = 0;
        }
    }
}
// Mostra layers
function show_tooltip(layer) {
     if(document.getElementById(layer).style.display == 'none'){
        document.getElementById(layer).style.display = 'block';
//        document.getElementById(layer).focus();
     }

     gravaCookieFormaPag(layer);

}

function gravaCookieFormaPag(layer){

    //<INPUT TYPE="HIDDEN" NAME="loja" VALUE="110">
	var http = getHTTPObject();
    var url = document.formPedido.urlformaPag.value+'?loja_id='+document.frmLoja.loja.value+"&formas="+layer;
    http.open("GET", url, true);
    //http.onreadystatechange = function(){ }//alert(http.responseText); };
    http.send(null);

}
//Verifica o valor digitado
function VerValorDigit(numero,moeda) {

    var objRegExp = /[^0-9]+/g;
    var valor = numero.value;
    valor = valor.replace(objRegExp,"");

    var re0 = /^[0-9\\/]+$/;

    if (!re0.test(valor)){
        valor = valor.substring(0,valor.length-1);
    }
    var tamanho = valor.length
    var milhar,centavos;

    if ((moeda == "US") || (moeda == "DR")){
        milhar=',';
        centavos='.';
    } else {
        milhar='.';
        centavos=',';
    }

    if (tamanho <= 5 && tamanho > 2){
        numero.value = valor.substring(0,valor.length - 2) + centavos + valor.substring(valor.length -2,valor.length);
    } else if (tamanho >= 6){

        var quociente = (tamanho - 2) / 3;
        var aux = 5;
        while (quociente >= 1){
            if ( (valor.length - aux) != 0 ){
                valor = valor.substring(0,valor.length - aux) + milhar + valor.substring(valor.length - aux, valor.length);
            }
            aux += 4;
            quociente--;
        }
        numero.value = valor.substring(0,valor.length - 2) + centavos + valor.substring(valor.length -2,valor.length);
    } else {
        numero.value = valor;
    }
}

function SubmeterDoacao(acao) {
    var erro = 0;
    for(x=0;x<document.formPedido.elements.length;x++) {
        if (document.formPedido.elements[x].name.substring(0,3) == 'qtd') {
            var valor = document.formPedido.elements[x].value;
            valor = valor.replace(/R\$/,'');
            valor = valor.replace(/\,.+/,'');
            valor = valor.replace(/\./g,'');
            valor = valor.replace(/\D/g,'');
            document.formPedido.elements[x].value = valor;
            //if ((valor < 10) && (valor > 0)) {
            //    erro++;
            //    alert('O valor mínimo de doação é R$ 10,00');
            //}
        }
    }
    if (erro == 0) {
        SubmeterPedido(acao);
    }
}

function SelProdDoacao() {
    var valor;
    for(var x=0;x<document.formHome.doacao.length;x++) {
        if (document.formHome.doacao[x].checked == true) {
            if (document.formHome.valor.value == '') {
                valor = 0;
            } else {
                            valor = document.formHome.valor.value;
                            valor = valor.replace(/\,.+/,"");
                            valor = valor.replace(/\./g,"");
            }
            if (valor < 20) {
                alert('O valor mínimo de doação é R$ 20,00');
            } else {
                Loja('PE',document.formHome.doacao[x].value,'','','qtd='+valor);
            }
        }
    }
}

// Função para inclusão do código flash na loja

function IncluiSWF ($loja,$arquivo,$largura,$altura,$id){
     document.writeln("    <object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0' width='" + $largura + "' height='" + $altura + "' id='" + $id + "' name='" + $id + "'>");
     document.writeln("    <param name='movie' value='http://"+document.domain + "/" + $loja + "/imagens/" + $arquivo + "' />");
     document.writeln("  <param name='menu' value='false' />");
     document.writeln("    <param name='quality' value='high' />");
     document.writeln("  <param name='scale' value='noscale' />");
     document.writeln("  <param name='wmode' value='transparent' />");
     document.writeln("    <embed src='http://"+document.domain + "/" +  $loja + "/imagens/" + $arquivo + "' quality='high' wmode='transparent' pluginspage='http://www.macromedia.com/go/getflashplayer' type='application/x-shockwave-flash' menu='false' scale='noscale' width='" + $largura + "' height='" + $altura + "' id='" + $id + "' ></embed>");
     document.writeln("    </object>");
    }


function FormataCpf() {
  var key = event.keyCode;
  if (key == 9 || key == 13)
    return;
  var numKeys = ((key >= 48 && key <= 57) || (key >= 96 && key <= 105)) && !event.shiftKey && !event.altKey;
  if (numKeys) {
    var objCpf = event.srcElement
    var objRegExp = /(\.|\-)/g
    var valor = objCpf.value.replace(objRegExp,"")
    var tam = valor.length
    if (tam < 11)
      tam++
    if (tam <= 2)
      objCpf.value = valor
    if (tam > 2 && tam <= 5)
      objCpf.value = valor.substr(0, tam-2) + '-' + valor.substr(tam-2, tam)
    if (tam >= 6 && tam <= 8)
      objCpf.value = valor.substr(0, tam-5) + '.' + valor.substr(tam-5, 3) + '-' + valor.substr(tam-2, tam)
    if (tam >= 9 && tam <= 11)
      objCpf.value = valor.substr(0, tam-8) + '.' + valor.substr(tam-8, 3) + '.' + valor.substr(tam-5, 3) + '-' + valor.substr(tam-2, tam)
    return
  }
  var sysKeys = (key == 8 || key == 9 || (key >= 35 && key <= 46))
  if (!sysKeys)
    event.returnValue = false
}

function trataEntrada(campo,frase) {
    if (!(campo.value && campo.value != frase)) {
        campo.value = '';
    }
}

function trataSaida(campo,frase) {
    if (campo.value == '') {
        campo.value = frase;
    }
}

function ValidaEmail(email){
	var re2 = /^([a-z0-9\.\-\_]+)\@([a-z0-9\-\_]+\.{1})*?([a-z0-9]{2,3}){1}$/;
	email = email.toLowerCase();
	if (!re2.test(email)){
			return 0;
	}
	return 1;
}

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}

String.prototype.ltrim = function() {
    return this.replace(/^\s+/,"");
}

String.prototype.rtrim = function() {
    return this.replace(/\s+$/,"");
}

function desmarcaRadios(){

    for(var x=0;x<document.formDetalhe.length;x++) {

        if (document.formDetalhe.elements[x].name.substring(0,7) == 'qtd_det') {
            document.formDetalhe.elements[x].value = 0;
            document.formDetalhe.elements[x].checked = false;
        }
    }


}
// Variação sem select, página de detalhe
function ComprarVar() {
    var qtd = ''; var codigo = '';
    var qtd_campo = 0;
	var mFotos = 0;
    var ObjFotos;
    if(document.getElementById('fotos')){
        ObjFotos = document.getElementById('fotos');
		mFotos =  1;
    }
    
    for(var x=0;x<document.formDetalhe.length;x++) {

        if (document.formDetalhe.elements[x].name.substring(0,7) == 'qtd_det') {
            qtd_campo++;
            if (document.formDetalhe.elements[x].value >= 1) {
                qtd += document.formDetalhe.elements[x].value + '-';
                codigo += document.formDetalhe.elements[x].name.substring(7) + '|';

                //chamar o módulo de multiplas fotos
                if(mFotos ==1){
                    var prod_id = document.formDetalhe.prod_id.value;
                    var loja_id = document.formDetalhe.loja.value;
                    var http = getHTTPObject(); // We create the HTTP Object
                    var url = 'http://'+document.domain+'/cgi-bin/ajxDetalheMfotos.pl?lojaId='+loja_id+'&prodId='+prod_id+'&codigo_barra='+document.formDetalhe.elements[x].name.substring(7);
					http.open("GET", url, true);
                	http.onreadystatechange =function(){
						if (http.readyState == 4){
                            if(http.status == 200){
                                ObjFotos.innerHTML = '';
                                if (http.responseText != 'NAO_DADOS|') {
					ObjFotos.innerHTML = http.responseText;
				}
				preparaImagens();
                            }
                        }
                    }
                	http.send(null);
                }
            }
        }
    }

    document.formDetalhe.variacao.value = codigo;
    document.formDetalhe.qtd.value = qtd;

    if ((window.event && window.event.keyCode == 13) && (qtd_campo > 1) ) {
        if (qtd == '') {
            alert('Informe a quantidade');
        } else {
            document.formDetalhe.submit();
        }
    }

}

function VerSaudar(caixa) {
    if (document.getElementById(caixa)) {
        var hoje   = new Date();
        var hrs = hoje.getHours();
        if (hrs  <= "23") var msg = "Boa noite";
        if (hrs  <= "17") var msg = "Boa tarde";
        if (hrs  <= "12") var msg = "Bom dia";

        x = document.getElementById(caixa);
        var texto = x.innerHTML.replace("SAUDAR",msg);
        x.innerHTML = texto;
    }
}
// Época login
function abrir() {
    $("div#janelaLogin").show("fast");
}
function fechar() {
    $("div#janelaLogin").hide("fast");
}
// Época cep
function abrirDetalhe() {
    $("div#janelaCepDetalhe").show("fast");
}

// Fecha o Pop-up em modo Layer no site
// o Flash deve conter essa chamada para fechar por completo o Pop
function somePop()
{
    pDiv = document.getElementById('popDiv');
    pDiv.style.display='none';
}

// Funções relacionadas as visualizações dos produtos do Combo
function quickView(dis,bt){
	if (dis) {
		document.getElementById(bt).style.display = "block";
	}else{
		document.getElementById(bt).style.display = "none";
	}
}
function chamaInfo(prod_id){
	alert("Prod ID: "+prod_id);
}

function escondeVideo(status){
	if (document.getElementById('colVideo')) {
		if (status) {
			document.getElementById('colVideo').style.display = "block";
		}
		else {
			document.getElementById('colVideo').style.display = "none";
		}
	}
}
function AmpliarFoto2(imagem,largura,altura){
    var ampliar;
    if(imagem.indexOf('jpg') > -1 || imagem.indexOf('gif') > -1 || imagem.indexOf('png') > -1){
            if(largura == 0 || altura ==0){
                //fazer um ajax para pegar o tamanho das fotos pois isso aqui está dando um bug
                largura = image_1.width;
                altura = image_1.height;
            }
    
    if ((largura >=600) || (altura >=600)) {
        if (largura > altura) {
            altura = altura * (600 / largura);
            largura = 600;
        } else if (altura > largura) {
            largura = largura * (600 / altura);
            altura = 600;
        } else {
            largura = 600;
            altura = 600;
        }
    }
    
	if(window.ampliar){
		ampliar.close();
    }
    
    imagem  = imagem.replace('..','');
    auxImagem = 'http://'+document.domain+imagem;
    ampliar = window.open('','ampliar','menubar=no,toolbar=no,status=no,directories=no,location=no,scrollbars=1,resizable=yes,width='+largura+',height='+altura+',top=20,left=20');
    ampliar.focus();
    ampliar.document.open("text/html");
    ampliar.document.write('<html><head><title>Imagem Ampliada</title></head><body bgcolor="#FFFFFF" text="#000000" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" scroll="auto"><a href="javascript:window.close();"><img src="'+auxImagem+'" width="'+largura+'" height="'+altura+'" border="0" alt="Clique na imagem para fechar a janela"></a></body></html>');
    ampliar.document.close();
    ampliar.onblur = function(){
                ampliar.close();
            }
    }
}

//tira os produtos do carrinho
function limpaCarrinho() {
	for(var x=0;x<document.formPedido.elements.length;x++){
		var nome = document.formPedido.elements[x].name;
		if (nome.indexOf('qtd') > -1) {
			document.formPedido.elements[x].value = 0;
		}
	}
}

//inclui campo informativo
function insereCampoInformativo(){
	if ($("#campo_informativo"))
	{
		var atributo = $("#campo_informativo").attr("class").replace("campoInfo_","");		// o nome da class contem qual será o nome do campo informativo
		document.frmLoja.campo_informativo.value = atributo + ": " + $("#campo_informativo").val();		// nome: valor
	}
}


// caixa de mensagem personalizada
// function showObjeto(obj, config){
// 
// 	var setting = initShowObjeto(obj, config);
// 	
// 	$("body").append('<div id="fundoMask"></div>');
// 	$("#fundoMask").css({opacity: setting['opacityFundo'],
// 						position: setting['positionFundo'],
// 						zIndex: setting['zIndexFundo'],
// 						top: setting['topFundo'],
// 						left: setting['leftFundo'],
// 						width : setting['widthFundo'],
// 						height : setting['heightFundo'],
// 						backgroundColor: setting['corFundo']});
// 						
// 	$(obj).css({left: setting['leftObj'], 
// 				top: setting['topObj'], 
// 				zIndex: setting['zIndexObj']}).fadeIn();
// 	
// 	if (setting['resize']){
// 		$(window).bind("resize", function(){
// 			if (setting['positionObj'] == 'absolute')
// 			{
// 				var posX = ajustaPosicaoX(setting['widthObj']);
// 				var posY = ajustaPosicaoY(setting['heightObj']);
// 				$(obj).css({left: posX, top: posY});
// 				$("#fundoMask").css({width: $(document).width(), 
// 									height: $(document).height()});
// 			}		
// 		} );
// 	}
// 	
// 	if (setting['scroll']){
// 		$(window).bind("scroll", function(){
// 			if (setting['positionObj'] == 'absolute')
// 			{
// 				var posX = ajustaPosicaoX(setting['widthObj']);
// 				var posY = ajustaPosicaoY(setting['heightObj']);
// 				$(obj).css({left: posX, top: posY});
// 			}
// 		} );
// 	}
// 	
// 	$(setting['idObjFechar']).bind("click" , function(){
// 		$(this).fadeOut();
// 		$(window).unbind("resize");
// 		$(window).unbind("scroll");
// 		$(this).unbind("click");
// 		$("#fundoMask").remove();
// 	} );
// }
// 
// passando a largura de um objeto, a função retorna a posição para centralizar na tela
// function ajustaPosicaoX (largura){
// 	return ((parseInt($(window).width() - largura) /2) + $(window).scrollLeft());
// }
// 
// passando a altura de um objeto, a função retorna a posição de um quarto na tela
// function ajustaPosicaoY (altura){
// 	return ((parseInt($(window).height() - altura) / 4) + $(window).scrollTop());
// }
// 
// retorna a largura de um objeto
// function pegaLargura(obj){
// 	var largura;
// 	if ($(obj).attr("width")){
// 		largura = $(obj).attr("width").replace("px","");
// 	} else if($(obj).css("width")){
// 		largura = $(obj).css("width").replace("px","");
// 	} else {
// 		largura = 0;
// 	}
// 	return largura;
// }
// 
// retorna a altura de um objeto
// function pegaAltura(obj){
// 	var altura;
// 	if ($(obj).attr("height")){
// 		altura = $(obj).attr("height").replace("px","");
// 	} else if ($(obj).css("height")){
// 		altura = $(obj).css("height").replace("px","");
// 	} else {
// 		altura = 0;
// 	}
// 	return altura;
// }
// 
// inicializar os parametros da função showObjeto()
// function initShowObjeto(obj, config){
// 	var objAltura = pegaAltura($(obj));
// 	var objLargura = pegaLargura($(obj));
// 	var objPosX = ajustaPosicaoX(objLargura);
// 	var objPosY = ajustaPosicaoY(objAltura);
// 	
// 	// padrão do plano de fundo
// 	var configPadrao = {};
// 	var retorno = {};
// 	
// 	configPadrao['positionFundo'] = "absolute";
// 	configPadrao['corFundo'] = "white";
// 	configPadrao['opacityFundo'] = "0.8";
// 	configPadrao['zIndexFundo'] = "990";
// 	configPadrao['topFundo'] = "0";
// 	configPadrao['leftFundo'] = "0";
// 	configPadrao['widthFundo'] = $(document).width();
// 	configPadrao['heightFundo'] = $(document).height();
// 	configPadrao['idObjFechar'] = obj;
// 	// padrão do objeto
// 	configPadrao['positionObj'] = "absolute";
// 	configPadrao['opacityObj'] = "1";
// 	configPadrao['zIndexObj'] = "995";
// 	configPadrao['topObj'] = objPosY;
// 	configPadrao['leftObj'] = objPosX;
// 	configPadrao['widthObj'] = objLargura;
// 	configPadrao['heightObj'] = objAltura;
// 	// padrão da função
// 	configPadrao['resize'] = true;
// 	configPadrao['scroll'] = true;
// 	
// 	if (!config['corFundo']){
// 		config['opacityFundo'] = "0";
// 	}
// 	
// 	$.extend(retorno, configPadrao, config);
// 	
// 	return retorno;
// }
