$(document).ready(function() {
	Sexy = new SexyAlertBox();
	SexyLightbox = new SexyLightBox({color:'white', dir: '../box/sexyimages', OverlayStyles : { 'width': '600px' } });
	
	var t = new Tips('.tip');
	$$('.tip').each(function(tip){
		var imgSrc = tip.retrieve('tip:text');
		var imgAlt = tip.retrieve('tip:title');
		var classe = 'tooltip';
		tip.store('tip:text', new Element('img',{'src':imgSrc,'alt':imgAlt,'class':classe}));
	});
});

function verificaInsumo(id, idbox, classe, tipo) {
	if(tipo == "1") {
		
		if($("#"+id).attr("rel") != 'clicado') {
			$("#"+id).attr("rel","clicado");
			$("#"+id).css("background-color","#99BE3D");
			$("#"+id).css("border-color","#759D15");
			$("#"+idbox).attr("checked",true);
		}
		else {
			$("#"+id).attr("rel","");
			$("#"+id).css("background-color","#F5F5F5");
			$("#"+idbox).attr("checked",false);
			$("#"+id).css("border-color","#DDDDDD");
		}
	}
	else { 
		$("[name^="+classe+"]").attr("rel","");
		$("[name^="+classe+"]").css("background","#F5F5F5");
		$("[name^="+classe+"]").css("border-color","#DDDDDD");
		$("#"+id).attr("rel","clicado");
		$("#"+id).css("background","#99BE3D");
		$("#"+id).css("border-color","#759D15");
		$("#"+idbox).click();
	}
}

function confirmacao(pergunta, acao1, acao2){
		var confirma = window.confirm(pergunta);
		if (confirma) { 
			if(acao1 != '') {
				window.location.href = acao1;
			}
			return true;
		}
		else { return false; }
}

function atualizaContador(YY,MM,DD,HH,MI,saida,reloade) {
var SS = 00; //Segundos
var hoje = new Date(); //Dia
var futuro = new Date(YY,MM-1,DD,HH,MI,SS); //Data limite do contador
 
var ss = parseInt((futuro - hoje) / 1000); //Determina a quantidade total de segundos que faltam
var mm = parseInt(ss / 60); //Determina a quantidade total de minutos que faltam
var hh = parseInt(mm / 60); //Determina a quantidade total de horas que faltam
var dd = parseInt(hh / 24); //Determina a quantidade total de dias que faltam
 
ss = ss - (mm * 60); //Determina a quantidade de segundos
mm = mm - (hh * 60); //Determina a quantidade de minutos
hh = hh - (dd * 24); //Determina a quantidade de horas

if(ss < 10) ss = '0'+ss;
if(mm < 10) mm = '0'+mm;
if(hh < 10) hh = '0'+hh;
 
//O bloco abaixo descreve monta o que vai ser escrito na tela
var faltam = 'Faltam ';
faltam += (dd && dd > 1) ? dd+' dias, ' : (dd==1 ? '1 dia, ' : '');
faltam += (toString(hh).length) ? hh+':' : '';
faltam += (toString(mm).length) ? mm+':' : '';
faltam += ss;
 
if (dd+hh+mm+ss > 0) {
document.getElementById(saida).innerHTML = faltam;//INsere o conteudo da variável faltam na página.
setTimeout(function(){atualizaContador(YY,MM,DD,HH,MI,saida,reloade)},1000);//Reinicia a função a cada um segundo
} else {
	document.getElementById(saida).innerHTML = 'Promo&ccedil;&atilde;o Encerrada!';
	if(reloade == '1') { window.location.reload() }
	else { setTimeout(function(){atualizaContador(YY,MM,DD,HH,MI,saida,reloade)},1000); }
}
}

function abreTabelaTapete() {
	SexyLightbox.show('', '../extras/tapetes.html?TB_iframe=true&amp;height=490&amp;width=800','sexylightbox');
	window.location.href = '#descprod';
}

function submitenter(myfield,e)
{
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;
	
	if (keycode == 13)
	   {
	   myfield.form.submit();
	   return false;
	   }
	else
	   return true;
}

function verificaCaracterPers(tipo, id, e){
	var tecla = (window.event)?event.keyCode:e.which;

	if(tipo == 'nome') {
		if(tecla == 14 || tecla == 15 || tecla == 32 || tecla == 46 || tecla >= 65) {}
		else{
			if (tecla != 8 && tecla != 0) return false;
		}
	}
	if(tipo == 'numero') {
		if ((tecla < 48 || tecla > 57) && (tecla != 8 && tecla != 0)) return false;
	}
}

function verificaCadastro(campo, valor, i) {
	$.post('../procedimentos/existe', { campo: campo, valor: valor }, function(data) {
		if(data != '') {
		//window.alert(data);
			var mensagem = 'Identificamos seu cadastro em nosso banco de dados.';
			if(data == '1') {
				mensagem += ' Implantamos uma nova plataforma com tecnologia criptografada dos dados dos nossos clientes. Por favor insira uma senha para concluir sua compra.';
				var conf = window.confirm(mensagem);
				if(conf) { window.location.href = 'texto/lembrete-de-senha/inserir'; }
				else  return false;
			}
			else if(data == '') {
				var mensagem2 = mensagem +' Deseja receber um lembrete de senha no seu email?';
				var conf = window.confirm(mensagem2);
				if(conf) { window.location.href = 'texto/lembrete-de-senha'; }
				else  return false;
			}
		}
		return false;
	});
}

function verificaCadastroVazio(campo, valor, i) {
	$.post('../procedimentos.php/naoexiste', { campo: campo, valor: valor }, function(data) {
		if(data != '') {
			
			var mensagem = 'Verificamos que seu cadastro nao foi migrado para o novo site.';
			if(data == 'Usuario nao existe') {
				mensagem += ' Efetue seu cadastro novamente e seja bem vindo.';
				var conf = window.confirm(mensagem);
				if(conf) { window.location.href = 'cadastro'; }
				else  return false;
			}
			
		}
		return false;
	});
}

function formataMaiusculo(id){
	var sStr = document.getElementById(id).value.toUpperCase();
	sStr = sStr.replace(/\//gi,'');
	sStr = sStr.replace(/\\/gi,'');
	document.getElementById(id).value = sStr;
}

function comprar(end, idcarrinho, totalProds){
	confereCarrinho(idcarrinho, totalProds, end);
}

function atualizaDiferenca(campo1, campo2, destino){
	var diferenca = parseFloat(campo2) - parseFloat(campo1);
	document.getElementById(destino).value = float2moeda(diferenca);
}

function atualizaDiferenca2(campo1, campo2, destino){
	var diferenca = parseFloat(campo2) + parseFloat(campo1);
	if(diferenca < 0) { $("#tbPagamento").hide(); $("#statusPagamento").html("Voc&ecirc; ter&aacute; dispon&iacute;vel R$ "+float2moeda(diferenca).replace('- ','')+" de cr&eacute;dito na pr&oacute;xima compra."); }
	else if(diferenca == 0) { $("#tbPagamento").hide(); $("#statusPagamento").html(""); }
	else { $("#tbPagamento").show(); $("#statusPagamento").html(""); }
	document.getElementById(destino).value = float2moeda(diferenca);
}

function pontovirgula(id) {
	var valor = document.getElementById(id).value;
	document.getElementById(id).value = valor.replace(/,/gi, ".");
}

function abreFotoThumb(endereco,zoom){
	document.getElementById('fotogrande').src = endereco;
	if(zoom == '1') {
		var enderecozoom = endereco.replace('1.jpg','2.jpg');
		document.getElementById('fotogrande').alt = enderecozoom;
	}
	else {
		document.getElementById('fotogrande').alt = '';
	}
}

function addFav(url, title){
    if (window.sidebar) window.sidebar.addPanel(title, url,"");
    else if(window.opera && window.print){
        var mbm = document.createElement('a');
        mbm.setAttribute('rel','sidebar');
        mbm.setAttribute('href',url);
        mbm.setAttribute('title',title);
        mbm.click();
    }
    else if(document.all){window.external.AddFavorite(url, title);}
}

function validaEmail(acao, input, form)
{
  var obj = document.getElementById(input);
  var txt = obj.value;
  if (txt.indexOf("@") < 1)
  {
    Sexy.alert('Email incorreto!');
  }
  else {
 	document.getElementById(form).action = acao;
	document.getElementById(form).submit();
  }
}

function validaTelefone(tel){
	if(tel.indexOf('0000-0000') >= 0 || tel.indexOf('1111-1111') >= 0 || tel.indexOf('2222-2222') >= 0 || tel.indexOf('3333-3333') >= 0 || tel.indexOf('4444-4444') >= 0 || tel.indexOf('5555-5555') >= 0 || tel.indexOf('6666-6666') >= 0 || tel.indexOf('7777-7777') >= 0 || tel.indexOf('8888-8888') >= 0 || tel.indexOf('9999-9999') >= 0 || tel == null) {
		return false
	}
	else {
		return true;
	}
}

function mensagem(texto) {
	Sexy.alert(texto);
}

function abreCategoria(div,total){
	for(i=0; i<total; i++) {
		if(document.getElementById('categoria'+i) != null) {
			document.getElementById('categoria'+i).style.display = 'none';
		}
	}
	document.getElementById('categoria'+div).style.display = 'inline';
}

function ajustaNome(valor) {
	   var retornar1 = valor.replace('digite aqui a palavra-chave','');
	   var retornar2 = retornar1.replace(/ /gi,'-');
	   var retornar3 = retornar2.replace(/º/gi,'_');
	   var teste = retornar3.replace(/â/gi,'a');
	   return teste;
} 


function buscar(url, busca) {
	var busca = ajustaNome(document.getElementById(busca).value);
	window.location.href = url+'busca/'+retira_acentos(busca.toLowerCase());
}

function chr(code)
{
	return String.fromCharCode(code);
}

function code2utf(code)
{
	if (code < 128) return chr(code);
	if (code < 2048) return chr(192+(code>>6)) + chr(128+(code&63));
	if (code < 65536) return chr(224+(code>>12)) + chr(128+((code>>6)&63)) + chr(128+(code&63));
	if (code < 2097152) return chr(240+(code>>18)) + chr(128+((code>>12)&63)) + chr(128+((code>>6)&63)) + chr(128+(code&63));
}

function _utf8Decode(utf8str)
{	
	var str = new Array();
	var code,code2,code3,code4,j = 0;
	for (var i=0; i<utf8str.length; ) {
		code = utf8str.charCodeAt(i++);
		if (code > 127) code2 = utf8str.charCodeAt(i++);
		if (code > 223) code3 = utf8str.charCodeAt(i++);
		if (code > 239) code4 = utf8str.charCodeAt(i++);
		
		if (code < 128) str[j++]= chr(code);
		else if (code < 224) str[j++] = chr(((code-192)<<6) + (code2-128));
		else if (code < 240) str[j++] = chr(((code-224)<<12) + ((code2-128)<<6) + (code3-128));
		else str[j++] = chr(((code-240)<<18) + ((code2-128)<<12) + ((code3-128)<<6) + (code4-128));
	}
	return str.join('');
}

function utf8Decode(utf8str)
{
	var str = new Array();
	var pos = 0;
	var tmpStr = '';
	var j=0;
	while ((pos = utf8str.search(/[^\x00-\x7F]/)) != -1) {
		tmpStr = utf8str.match(/([^\x00-\x7F]+[\x00-\x7F]{0,10})+/)[0];
		str[j++]= utf8str.substr(0, pos) + _utf8Decode(tmpStr);
		utf8str = utf8str.substr(pos + tmpStr.length);
	}
	
	str[j++] = utf8str;
	return str.join('');
}

function retira_acentos(palavra) {
	com_acento = utf8Decode("áàãâäéèêëíìîïóòõôöúùûüçÁÀÃÂÄÉÈÊËÍÌÎÏÓÒÕÖÔÚÙÛÜÇº'");
	sem_acento = "aaaaaeeeeiiiiooooouuuucAAAAAEEEEIIIIOOOOOUUUUC__";
	nova='';
	for(i=0;i<palavra.length;i++) {
		if (com_acento.search(palavra.substr(i,1))>=0) {
			nova+=sem_acento.substr(com_acento.search(palavra.substr(i,1)),1);
		}
		else {
			nova+=palavra.substr(i,1);
		}
	}
	return nova;
}
function urlencode(sStr) {
	sStr = escape(sStr);
	sStr = sStr.replace(/'/gi,'%27');
	sStr = sStr.replace(/"/gi,'%22');
	sStr = sStr.replace(/\//gi,'%2F');
	sStr = sStr.replace(/\+/gi,'%2B');
	return sStr;
}

function urlencode2(sStr) {
	if(sStr != null) {
		sStr = escape(sStr);
		sStr = sStr.replace(/'/gi,'%27');
		sStr = sStr.replace(/"/gi,'%22');
		sStr = sStr.replace(/\+/gi,'%2B');
		return sStr;
	}
}

function urldecode(str) {
 
    var histogram = {};
    var ret = str.toString();
 
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
 
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    histogram['\u20AC'] = '%80';
    histogram['\u0081'] = '%81';
    histogram['\u201A'] = '%82';
    histogram['\u0192'] = '%83';
    histogram['\u201E'] = '%84';
    histogram['\u2026'] = '%85';
    histogram['\u2020'] = '%86';
    histogram['\u2021'] = '%87';
    histogram['\u02C6'] = '%88';
    histogram['\u2030'] = '%89';
    histogram['\u0160'] = '%8A';
    histogram['\u2039'] = '%8B';
    histogram['\u0152'] = '%8C';
    histogram['\u008D'] = '%8D';
    histogram['\u017D'] = '%8E';
    histogram['\u008F'] = '%8F';
    histogram['\u0090'] = '%90';
    histogram['\u2018'] = '%91';
    histogram['\u2019'] = '%92';
    histogram['\u201C'] = '%93';
    histogram['\u201D'] = '%94';
    histogram['\u2022'] = '%95';
    histogram['\u2013'] = '%96';
    histogram['\u2014'] = '%97';
    histogram['\u02DC'] = '%98';
    histogram['\u2122'] = '%99';
    histogram['\u0161'] = '%9A';
    histogram['\u203A'] = '%9B';
    histogram['\u0153'] = '%9C';
    histogram['\u009D'] = '%9D';
    histogram['\u017E'] = '%9E';
    histogram['\u0178'] = '%9F';
 
    for (replace in histogram) {
        search = histogram[replace];
        ret = replacer(search, replace, ret)  
    }
 
    ret = decodeURIComponent(ret);
 
    return ret;
}

function atualizaValorCarrinho(descontar) {
	document.getElementById('valorCarrinho').value -= parseFloat(descontar);
	var valorCarrinho = document.getElementById('valorCarrinho').value;
	
	if(valorCarrinho <= 0) {
		document.getElementById('semresultado').style.display = 'block';
		document.getElementById('titulosCampo').style.display = 'none';
		document.getElementById('baixoCarrinhoTotal').style.display = 'none';
	}
	
	$('#valorTotalCarrinho').html('R$ '+float2moeda(valorCarrinho));
}

function float2moeda(num) {
	x = 0;
	
	if(num<0) {
	num = Math.abs(num);
	x = 1;
	} if(isNaN(num)) num = "0";
	cents = Math.floor((num*100+0.5)%100);
	
	num = Math.floor((num*100+0.5)/100).toString();
	
	if(cents < 10) cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+'.'
	+num.substring(num.length-(4*i+3)); ret = num + ',' + cents; if (x == 1) ret = ' - ' + ret;return ret;
}

function fecharBox() {
	SexyLightbox.close();
}

function confereCarrinho(id, totalProds, end) {
	var totalProds = parseFloat(totalProds) + 1;
	var obs = 0;
	for(i=1;i<totalProds;i++) {
		var valorSub = $("#sub"+i).val();
		
		if(document.getElementById('sub'+i) != null && valorSub == 'SELECIONE') {
			obs = 1;
			$("#sub"+i).css("border", "2px solid red");
		}
		else if(document.getElementById('sub'+i) != null) {
			
		}
	}
	if(obs == 1) { Sexy.alert('Escolha o tamanho desejado.'); }
	else {  window.location.href = end+'envio'; }
}

function Verifica_CPF(cpf) {
	  cpf = cpf.replace('-','');
	  cpf = cpf.replace(".", "");
	  cpf = cpf.replace(".", "");
		  
      var numeros, digitos, soma, i, resultado, digitos_iguais;
      digitos_iguais = 1;
      if (cpf.length < 11)
            return false;
      for (i = 0; i < cpf.length - 1; i++)
            if (cpf.charAt(i) != cpf.charAt(i + 1))
                  {
                  digitos_iguais = 0;
                  break;
                  }
      if (!digitos_iguais)
            {
            numeros = cpf.substring(0,9);
            digitos = cpf.substring(9);
            soma = 0;
            for (i = 10; i > 1; i--)
                  soma += numeros.charAt(10 - i) * i;
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(0))
                  return false;
            numeros = cpf.substring(0,10);
            soma = 0;
            for (i = 11; i > 1; i--)
                  soma += numeros.charAt(11 - i) * i;
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(1))
                  return false;
            return true;
            }
      else
            return false;
}


function Verifica_Email(mail){
  if ((mail.length != 0) && ((mail.indexOf("@") < 1)))
  { return false; }
  else { return true; }
}

function Verifica_CNPJ(cnpj)
{
	var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
	digitos_iguais = 1;
	if (cnpj.length < 14 && cnpj.length < 15)
		return false;
	for (i = 0; i < cnpj.length - 1; i++)
		if (cnpj.charAt(i) != cnpj.charAt(i + 1))
			  {
			  digitos_iguais = 0;
			  break;
			  }
	if (!digitos_iguais)
		{
		tamanho = cnpj.length - 2
		numeros = cnpj.substring(0,tamanho);
		digitos = cnpj.substring(tamanho);
		soma = 0;
		pos = tamanho - 7;
		for (i = tamanho; i >= 1; i--)
			  {
			  soma += numeros.charAt(tamanho - i) * pos--;
			  if (pos < 2)
					pos = 9;
			  }
			  
		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
		if (resultado != digitos.charAt(0))
		tamanho = tamanho + 1;
		numeros = cnpj.substring(0,tamanho);
		soma = 0;
		pos = tamanho - 7;
		for (i = tamanho; i >= 1; i--)
			  {
			  soma += numeros.charAt(tamanho - i) * pos--;
			  if (pos < 2)
					pos = 9;
			  }
		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
		if (resultado != digitos.charAt(1))
		return true;
		}
	else
		return false;
} 

function Verifica_Data(digData) {
	var bissexto = 0;
	var data = digData;
	var tam = data.length;
	if (tam == 10)
	{
		var dia = data.substr(0,2)
		var mes = data.substr(3,2)
		var ano = data.substr(6,4)
		if ((ano > 1900)||(ano < 2100))
		{
			switch (mes)
			{
				case '01':
				case '03':
				case '05':
				case '07':
				case '08':
				case '10':
				case '12':
				if  (dia <= 31)
				{
					return true;
					}
					break
					case '04':
					case '06':
					case '09':
					case '11':
					if  (dia <= 30)
					{
						return true;
						}
						break
						case '02':                                        
						if ((ano % 4 == 0) || (ano % 100 == 0) || (ano % 400 == 0)){
							bissexto = 1;
							}
							if ((bissexto == 1) && (dia <= 29))
							{
								return true;
							}
							if ((bissexto != 1) && (dia <= 28))
							{
								return true;
							}
							break
						}
					}
				}
	return false;
}

function verifica_Cartao(cardNumber, cardType){
    var isValid = false; 
    var ccCheckRegExp = /[^\d ]/;
    isValid = !ccCheckRegExp.test(cardNumber);
    if (isValid){
        var cardNumbersOnly = cardNumber.replace(/ /g,"");
        var cardNumberLength = cardNumbersOnly.length;
        var lengthIsValid = false;
        var prefixIsValid = false;
        var prefixRegExp;
    switch(cardType){
        case "6":
            lengthIsValid = (cardNumberLength == 16);
            prefixRegExp = /^5[1-5]/;
        break;
        case "7":
            lengthIsValid = (cardNumberLength == 16 || cardNumberLength == 13);
            prefixRegExp = /^4/;
        break;
        case "8":
            lengthIsValid = (cardNumberLength == 15);
            prefixRegExp = /^3(4|7)/;
        break;
        default:
            prefixRegExp = /^$/;
    }

    prefixIsValid = prefixRegExp.test(cardNumbersOnly);
    isValid = prefixIsValid && lengthIsValid;
    }
    return isValid;
}

function doIframe(){
	o = document.getElementsByTagName('iframe');
	for(i=0;i<o.length;i++){
		if (/\bautoHeight\b/.test(o[i].className)){
			setHeight(o[i]);
			addEvent(o[i],'load', doIframe);
		}
	}
}

function setHeight(e){
	if(e.contentDocument){
		e.height = e.contentDocument.body.offsetHeight + 35;
	} else {
		e.height = e.contentWindow.document.body.scrollHeight;
	}
}

function addEvent(obj, evType, fn){
	if(obj.addEventListener)
	{
	obj.addEventListener(evType, fn,false);
	return true;
	} else if (obj.attachEvent){
	var r = obj.attachEvent("on"+evType, fn);
	return r;
	} else {
	return false;
	}
}

if (document.getElementById && document.createTextNode){
 addEvent(window,'load', doIframe);	
}

