/*
		JS CODE FOR CAMISETAS ÁGAPE'S WEBSITE!
		CÓPIA PROIBIDA DE ACORDO COM A LEI Nº 9.610, DE 19 DE FEVEREIRO DE 1998.
		DESENVOLVIDO POR STUDIO XY - www.studioxy.com.br
*/

/*SLIDER*/
window.onerror=function(desc,page,line,chr){
/* alert('JavaScript error occurred! \n'
  +'\nError description: \t'+desc
  +'\nPage address:      \t'+page
  +'\nLine number:       \t'+line
 );*/
}

jQuery(function(){
 jQuery('a').focus(function(){this.blur();});
 SI.Files.stylizeAll();
 slider.init();

 jQuery('input.text-default').each(function(){
  jQuery(this).attr('default',jQuery(this).val());
 }).focus(function(){
  if(jQuery(this).val()==jQuery(this).attr('default'))
   jQuery(this).val('');
 }).blur(function(){
  if(jQuery(this).val()=='')
   jQuery(this).val(jQuery(this).attr('default'));
 });

 jQuery('input.text,textarea.text').focus(function(){
  jQuery(this).addClass('textfocus');
 }).blur(function(){
  jQuery(this).removeClass('textfocus');
 });

 var popopenobj=0,popopenaobj=null;
 jQuery('a.popup').click(function(){
  var pid=jQuery(this).attr('rel').split('|')[0],_os=parseInt(jQuery(this).attr('rel').split('|')[1]);
  var pobj=jQuery('#'+pid);
  if(!pobj.length)
   return false;
  if(typeof popopenobj=='object' && popopenobj.attr('id')!=pid){
   popopenobj.hide(50);
   jQuery(popopenaobj).parent().removeClass(popopenobj.attr('id').split('-')[1]+'-open');
   popopenobj=null;
  }
  return false;
 });
 jQuery('p.images img').click(function(){
  var newbg=jQuery(this).attr('src').split('bg/bg')[1].split('-thumb')[0];
  jQuery(document.body).css('backgroundImage','url('+_siteRoot+'images/bg/bg'+newbg+'.jpg)');
 
  jQuery(this).parent().find('img').removeClass('on');
  jQuery(this).addClass('on');
  return false;
 });
 jQuery(window).load(function(){
	 var css_ims = this;
	 var css_cims = this;
  $.each(css_ims,function(){(new Image()).src=_siteRoot+'css/images/'+this;});
  $.each(css_cims,function(){
   var css_im=this;
   $.each(['blue','purple','pink','red','grey','green','yellow','orange'],function(){
    (new Image()).src=_siteRoot+'css/'+this+'/'+css_im;
   });
  });
 }); 
 jQuery('div.sc-large div.img:has(div.tml)').each(function(){
  jQuery('div.tml',this).hide();
  jQuery(this).append('<a href="#" class="tml_open">&nbsp;</a>').find('a').css({
   left:parseInt(jQuery(this).offset().left)+864,top:parseInt(jQuery(this).offset().top)+1
  }).click(function(){
   jQuery(this).siblings('div.tml').slideToggle();
   return false;
  }).focus(function(){this.blur();}); 
 });
});
var slider={
 num:-1,
 cur:0,
 cr:[],
 al:null,
 at:10*1000, //esse 10 são os segundos que o slide ficará parado
 ar:true,
 init:function(){
  if(!slider.data || !slider.data.length)
   return false;

  var d=slider.data;
  slider.num=d.length;
  var pos=Math.floor(Math.random()*1);//slider.num);
  for(var i=0;i<slider.num;i++){
   jQuery('#'+d[i].id).css({left:((i-pos)*960)}); //esse 960 é paar setar o espaçamento entre as imagens
   jQuery('#slide-nav').append('<a id="slide-link-'+i+'" style="cursor:pointer;" onclick="slider.slide('+i+');return false;" onfocus="this.blur();">'+(i+1)+'</a>');
  }

  jQuery('img,div#slide-controls',jQuery('div#slide-holder')).fadeIn();
  slider.text(d[pos]);
  slider.on(pos);
  slider.cur=pos;
  window.setTimeout('slider.auto();',slider.at);
 },
 auto:function(){
  if(!slider.ar)
   return false;

  var next=slider.cur+1;
  if(next>=slider.num) next=0;
  slider.slide(next);
 },
 slide:function(pos){
  if(pos<0 || pos>=slider.num || pos==slider.cur)
   return;

  window.clearTimeout(slider.al);
  slider.al=window.setTimeout('slider.auto();',slider.at);

  var d=slider.data;
  for(var i=0;i<slider.num;i++)
   jQuery('#'+d[i].id).stop().animate({left:((i-pos)*960)},700,'swing'); //esse 960 é paar setar o espaçamento entre as imagens. o 700 é paar setar a velocidade que o slide passa
  
  slider.on(pos);
  slider.text(d[pos]);
  slider.cur=pos;
 },
 on:function(pos){
  jQuery('#slide-nav a').removeClass('on');
  jQuery('#slide-nav a#slide-link-'+pos).addClass('on');
 },
 text:function(di){
  slider.cr['a']=di.client;
  slider.cr['b']=di.desc;
  slider.ticker('#slide-client span',di.client,0,'a');
  slider.ticker('#slide-desc',di.desc,0,'b');
 },
 ticker:function(el,text,pos,unique){
  if(slider.cr[unique]!=text)
   return false;

  ctext=text.substring(0,pos)+(pos%2?'':'');
  jQuery(el).html(ctext);

  if(pos==text.length)
   jQuery(el).html(text);
  else
   window.setTimeout('slider.ticker("'+el+'","'+text+'",'+(pos+1)+',"'+unique+'");',10); // esse 10 é a velicidade em que a descrição é escrita, quanto maior, mais lento
 }
};
// STYLING FILE INPUTS 1.0 | Shaun Inman <http://www.shauninman.com/> | 2007-09-07
if(!window.SI){var SI={};};
SI.Files={
 htmlClass:'SI-FILES-STYLIZED',
 fileClass:'file',
 wrapClass:'cabinet',
 
 fini:false,
 able:false,
 init:function(){
  this.fini=true;
 },
 stylize:function(elem){
  if(!this.fini){this.init();};
  if(!this.able){return;};
  
  elem.parentNode.file=elem;
  elem.parentNode.onmousemove=function(e){
   if(typeof e=='undefined') e=window.event;
   if(typeof e.pageY=='undefined' &&  typeof e.clientX=='number' && document.documentElement){
    e.pageX=e.clientX+document.documentElement.scrollLeft;
    e.pageY=e.clientY+document.documentElement.scrollTop;
   };
   var ox=oy=0;
   var elem=this;
   if(elem.offsetParent){
    ox=elem.offsetLeft;
    oy=elem.offsetTop;
    while(elem=elem.offsetParent){
     ox+=elem.offsetLeft;
     oy+=elem.offsetTop;
    };
   };
  };
 },
 stylizeAll:function(){
  if(!this.fini){this.init();};
  if(!this.able){return;};
 }
};

/* LOAD PAGE FUNCTION */
function loadRep(pagina){
		jQuery("#rep_right").replaceWith("<div id=\"rep_right\"></div>");
        jQuery("#rep_right").append("<img src='/images/loader.gif'>");
        jQuery('#rep_right').load('reps/'+pagina+'.html', function() {
        jQuery("#rep_right").append("");
        });
}
function loadDist(pagina){
		jQuery("#rep_right").replaceWith("<div id=\"rep_right\"></div>");
        jQuery("#rep_right").append("<img src='/images/loader.gif'>");
        jQuery('#rep_right').load('dist/'+pagina+'.html', function() {
        jQuery("#rep_right").append("");
        });
}
function loadWhere(pagina){
		jQuery("#rep_right").replaceWith("<div id=\"rep_right\"></div>");
        jQuery("#rep_right").append("<img src='/images/loader.gif'>");
        jQuery('#rep_right').load('where/'+pagina+'.html', function() {
        jQuery("#rep_right").append("");
        });
}

function colection_create(id){
		$('#'+id+' .caption').css({opacity: 0.8});
		$('#'+id+' .caption').css({width: $('#'+id+' a').find('img').css('width')});
		$('#'+id+' .cont').html($('#'+id+' a:first').find('img').attr('rel'));
}
function checkMail(mail){
	er = /^[a-zA-Z0-9][a-zA-Z0-9\._-]+@([a-zA-Z0-9\._-]+\.)[a-zA-Z-0-9]{2}/;
	if (er.exec(mail)){
		return true;
	}
	else{
		return false;
	}
}
function remove(str, sub) {
   i = str.indexOf(sub);
   r = "";
   if (i == -1) return str;
   r += str.substring(0,i) + remove(str.substring(i + sub.length), sub);
   return r;
 }
 
function validaCPF(){
	cpf = document.getElementById('cpf').value
	cpf = remove(cpf, "-");
	cpf = remove(cpf, ".");
	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 validaCNPJ() {
	CNPJ = document.getElementById('cnpj').value;
	erro = new String;
	if (CNPJ.length < 18) erro += "É necessario preencher corretamente o número do 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 CNPJ! \n\n";
	}
	//substituir os caracteres que não sã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çã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){
		return false;
	} else {
		return true;
	}
}
function valida_senha(){ 
	if (!document.getElementById('concordo').checked){
		checaCampo("concordo","Você deve concordar com os termos de uso");
	}
	if (document.getElementById('ref1n').value == ''){
		checaCampo("ref1n","Informe um nome para referência");
	}
	if ((document.getElementById('ref1').value == '') || (document.getElementById('ref1').value == '(__) ____-____')){
		checaCampo("ref1","Informe um telefone para referência");
	}
	if ((document.getElementById('telefone').value == '') || (document.getElementById('telefone').value == '(__) ____-____')){
		checaCampo("telefone","Insira o seu telefone");
	}
	if (document.getElementById('pais').value == '33'){
		if ((document.getElementById('cep').value == '') || (document.getElementById('cep').value == '_____-__')){
			checaCampo("cep","Insira o CEP");
		}
	}
	else {
		if (document.getElementById('cep2').value == ''){
			checaCampo("cep2","Insira o Código Postal");
		}
	}
	if (document.getElementById('endereco').value == ''){
		checaCampo("endereco","Insira o Endereço");
	}
	if (document.getElementById('pais').value == '33'){
		if (document.getElementById('cidade').value == ''){
			checaCampo("cidade","Selecione a cidade");
		}
	}
	else {
		if (document.getElementById('cidade2').value == ''){
			checaCampo("cidade2","Selecione a cidade");
		}
	}
	if (document.getElementById('pais').value == '33'){
		if (document.getElementById('estado').value == ''){
			checaCampo("estado","Selecione o estado");
		}
	}
	else {
		if (document.getElementById('estado2').value == ''){
			checaCampo("estado2","Selecione o estado");
		}
	}
	if (document.getElementById('senha2').value.length < 6){
		checaCampo("senha2","Confirme a senha");
	}
	if (document.getElementById('senha').value.length < 6){
		checaCampo("senha","Insira uma senha com pelo menos 6 caracteres");
	}
	if(document.cadastro.senha.value != document.cadastro.senha2.value) {
		checaCampo("senha2","A CONFIRMAÇÃO NÃO CONFERE COM A SENHA");
		checaCampo("senha","A SENHA NÃO CONFERE COM A CONFIRMAÇÃO");
	}
	if (document.getElementById('email').value == ''){
		checaCampo("email","Insira um email válido");
	}
	else {
		er = /^[a-zA-Z0-9\._-]+@([a-zA-Z0-9\._-]+\.)[a-zA-Z-0-9]{2}/;
		if(!er.exec(document.getElementById('email').value)){
			checaCampo("email","Este não é um email válido");
		}
	}
	if (document.getElementById('sobrenome').value == ''){
		checaCampo("sobrenome","Insira seu sobrenome");
	}
	if (document.getElementById('nome').value == ''){
		checaCampo("nome","Insira seu nome");
	}
	if (document.cadastro.tipoPessoa[0].checked){
		if ((document.getElementById('cpf').value == '') || (document.getElementById('cpf').value == '___.___.___-__') || (!validaCPF())){
			checaCampo("cpf","Insira um CPF válido");
		}
	}
	else if (document.cadastro.tipoPessoa[1].checked){
		if (document.getElementById('ie').value == ''){
			if (!document.getElementById('ieisento').checked){
				checaCampo("ie","Insira a Inscrição Estadual");
			}
		}
		if ((document.getElementById('cnpj').value == '') || (document.getElementById('cnpj').value == '__.___.___/____-__') || (!validaCNPJ())){
			checaCampo("cnpj","Insira um CNPJ válido");
		}
		if (document.getElementById('empresa').value == ''){
			checaCampo("empresa","Insira o nome da empresa");
		}
	}
	if (campoFoco){
			document.getElementById('aviso-erro-cadastro').innerHTML = "Corrija ou complete os campos marcados em vermelho.";
			document.getElementById(campoFoco).focus();
			delete campoFoco;
			return false;
	}
}
function mudapais(){
	if (typeof document.body.style.maxHeight != "undefined") {
		if (document.getElementById('pais').value == '33'){
			document.getElementById('estado-box').style.display='table';
			document.getElementById('estado2-box').style.display='none';
			document.getElementById('cidade-box').style.display='table';
			document.getElementById('cidade2-box').style.display='none';
			document.getElementById('cep-box').style.display='table';
			document.getElementById('cep2-box').style.display='none';
		}
		else{
			document.getElementById('estado-box').style.display='none';
			document.getElementById('estado2-box').style.display='table';
			document.getElementById('cidade-box').style.display='none';
			document.getElementById('cidade2-box').style.display='table';
			document.getElementById('cep-box').style.display='none';
			document.getElementById('cep2-box').style.display='table';
		}
	}
	else {
		if (document.getElementById('pais').value == '33'){
			document.getElementById('estado-box').style.display='block';
			document.getElementById('estado2-box').style.display='none';
			document.getElementById('cidade-box').style.display='block';
			document.getElementById('cidade2-box').style.display='none';
			document.getElementById('cep-box').style.display='block';
			document.getElementById('cep2-box').style.display='none';
		}
		else{
			document.getElementById('estado-box').style.display='none';
			document.getElementById('estado2-box').style.display='block';
			document.getElementById('cidade-box').style.display='none';
			document.getElementById('cidade2-box').style.display='block';
			document.getElementById('cep-box').style.display='none';
			document.getElementById('cep2-box').style.display='block';
		}
	}
}
function CarregaCidades(codEstado,CITY){
	if (document.getElementById('estado').value != ''){
		jQuery("#cidade_carregada").replaceWith("<div class=\"cform-input\" id=\"cidade_carregada\"></div>");
		jQuery("#cidade-nfo").replaceWith("<div class=\"cform-nfo\" id=\"cidade-nfo\"></div>");
		jQuery("#estado-nfo").replaceWith("<div class=\"cform-nfo\" id=\"estado-nfo\"></div>");
		document.getElementById("estado").style.border='1px solid #B4B5B7';
		document.getElementById("estado").style.background='none';
		jQuery("#cidade_carregada").append("Carregando cidades...");
		if (CITY.value == "no"){
			jQuery('#cidade_carregada').load('/inc/carrega_cidades.php?codEstado='+codEstado, function() {
				jQuery("#cidade_carregada").append("");
			});
		}
		else {
			jQuery('#cidade_carregada').load('/inc/carrega_cidades.php?codEstado='+codEstado+'&city='+CITY, function() {
				jQuery("#cidade_carregada").append("");
			});
		}
	}
	else {
		jQuery("#cidade_carregada").replaceWith("<div class=\"cform-input\" id=\"cidade_carregada\"><select name=\"cidade\" id=\"cidade\" disabled=\"disabled\"><option value=\"\">Selecione o estado</option></select></div>");
	}
}
function tiracor(CAMPO){
	if (document.getElementById(CAMPO).value != ''){
		document.getElementById(CAMPO).style.border='1px solid #B4B5B7';
		document.getElementById(CAMPO).style.background='none';
		document.getElementById(CAMPO+'-nfo').innerHTML = "";
	}
	else if ((CAMPO == "ie") && (document.getElementById('ieisento').checked)) {
		document.getElementById(CAMPO).style.border='1px solid #B4B5B7';
		document.getElementById(CAMPO).style.background='none';
		document.getElementById(CAMPO+'-nfo').innerHTML = "";
	}
}
function IEisento(){
	if(document.getElementById('ieisento').checked){
		document.cadastro.ie.disabled = 1;
		document.getElementById('ie').value = "";
	}
	else {
		document.cadastro.ie.disabled = 0;
	}
}
function checaCampo(CAMPO,MENSAGEM){
	document.getElementById(CAMPO).style.border='1px solid #FF0000';
	document.getElementById(CAMPO).style.background='#FFCAD5';
	document.getElementById(CAMPO+'-nfo').innerHTML = MENSAGEM;
	campoFoco = CAMPO;
}
function valor_total(PRECO){
	if (PRECO)
	{
	document.getElementById('carrinho-valor').innerHTML = "Valor das compras: <strong>R$ "+PRECO+"</strong>";
	}
	else
	{
	document.getElementById('carrinho-valor').innerHTML = "<strong>O Carrinho de Compras está vazio</strong>.";	
	}
}
function verificaPessoa(ID){
	if (typeof document.body.style.maxHeight != "undefined") {
		if (ID == "PF"){
			document.getElementById('PJNomeEmpresa').style.display='none';
			document.getElementById('PJcnpj').style.display='none';
			document.getElementById('PJIE').style.display='none';
			document.getElementById('PFcpf').style.display='table';
			document.getElementById('nome-div').innerHTML = "<label for=\"nome\">Nome:*</label>";
		}else{
			document.getElementById('PJNomeEmpresa').style.display='table';
			document.getElementById('PJcnpj').style.display='table';
			document.getElementById('PJIE').style.display='table';
			document.getElementById('PFcpf').style.display='none';
			document.getElementById('nome-div').innerHTML = "<label for=\"nome\">Nome do responsável:*</label>";
		}
	}else{
		if (ID == "PF"){
			document.getElementById('PJNomeEmpresa').style.display='none';
			document.getElementById('PJcnpj').style.display='none';
			document.getElementById('PJIE').style.display='none';
			document.getElementById('PFcpf').style.display='block';
			document.getElementById('nome-div').innerHTML = "<label for=\"nome\">Nome:*</label>";
		}else{
			document.getElementById('PJNomeEmpresa').style.display='block';
			document.getElementById('PJcnpj').style.display='block';
			document.getElementById('PJIE').style.display='block';
			document.getElementById('PFcpf').style.display='none';
			document.getElementById('nome-div').innerHTML = "<label for=\"nome\">Nome do responsável:*</label>";
		}
	}
	
}
function checaCompra(ID){
	if (ID == "1"){
		document.getElementById('pagamento-primeira').style.display='block';
		document.getElementById('pagamento-normal').style.display='none';
	}else{
		document.getElementById('pagamento-primeira').style.display='none';
		document.getElementById('pagamento-normal').style.display='block';
	}
	
}
jQuery(document).ready(function() {
	jQuery("a[rel=galeria]").fancybox({
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'titlePosition' 	: 'over',
		'titleFormat'       : function(title, currentArray, currentIndex, currentOpts) {
		    return '<span id="fancybox-title-over">Imagem ' +  (currentIndex + 1) + ' de ' + currentArray.length + ' - ' + title + '</span>';
		}
	});
	$("img.lazyload").lazyload({
		placeholder : "images/spacer.gif",
		effect : "fadeIn"
	});
});


