$(function() {
	$.getScript('js/libs/jquery/jquery.metadata.js',function(){ //1
	$.getScript('js/libs/jquery/validate/jquery.validate.min.js',function(){ //2
	$.getScript('js/libs/jquery/validate/messages_ptbr.js',function(){ //3
	$.getScript('js/libs/jquery/jquery.query-2.1.6.js', function() { //4
	$.getScript('js/libs/jquery/star/jquery.rating.pack.js', function() { //5
	$.getScript('js/libs/jquery/mask/jquery.meio.mask.js', function() { //6
	$.getScript('js/libs/swfobject/swfobject.js', function() { //7
		//
		main();
	}); //7
	}); //6
	}); //5
	}); //4
	}); //3
	}); //2
	}); //1
});

Shadowbox.init({
	language: 'pt-br',
	handleOversize: 'drag',
	continuous: true,
	players: ['img', 'html', 'iframe', 'qt', 'wmp', 'swf', 'flv'],
	onFinish: function() {
		$('#sb-wrapper').show();
		if($('img',Shadowbox.getCurrent().el).attr('alt') != '' && $('img',Shadowbox.getCurrent().el).attr('alt') != undefined) {
			if($('#sb-caption').html() == null) $('#sb-body').after('<div id="sb-caption"><div id="sb-caption-inner"></div></div>');
			$('#sb-caption-inner').html($('img',Shadowbox.getCurrent().el).attr('alt'));
			$('#sb-caption').css({
					position: 'absolute',
					textAlign: 'center',
					color: '#FFFFFF',
					background: 'url(/legba/site/imgs/legendas.png) top',
					top: ($('#sb-body').position().top+$('#sb-body').height()-$('#sb-caption').height()+1) + 'px', //1 da borda
					width: ($('#sb-body').width()) + 1 + 'px'
				}).hide().slideDown('fast');
		}else{
			$('#sb-caption').hide('fast');
		}
	},
	onClose: function() {
		$('#sb-caption').hide();
	}
});

String.prototype.replaceAll = function(de, para){
    var str = this;
    var pos = str.indexOf(de);
    while (pos > -1){
		str = str.replace(de, para);
		pos = str.indexOf(de);
	}
    return (str);
}

var menuIdent = null;
var menuVelocidade = 'fast';
function main() {
	//Menus
	$('#menu>a, .submenu').mouseenter(function() {
		clearTimeout(menuIdent);
		if (!$(this).hasClass('submenu')) {
			submenu = $('#menu'+$('#menu>a').index(this));
			submenu.css({ left: $(this).offset().left + 'px', top: ($(this).offset().top + $(this).height() +
			parseInt($(this).css('padding-top').replace('px',''))+parseInt($(this).css('padding-bottom').replace('px',''))) + 'px' }).stop(true,true).slideDown(menuVelocidade);
			$('.submenu:not(#menu'+($('#menu>a').index(this))+')').slideUp(menuVelocidade, function() { $('#menu>a:eq('+$(this).attr('id').replace('menu','')+'):not(.ativo)').removeClass('submenuon cor3 fCor2'); });
			if (submenu.length > 0) $(this).addClass('submenuon cor3 fCor2');
		}
	}).mouseleave(function() {
		menuIdent = setTimeout(function() { $('.submenu').slideUp(menuVelocidade, function() { $('#menu>a:eq('+$(this).attr('id').replace('menu','')+'):not(.ativo)').removeClass('submenuon cor3 fCor2'); }); },500);
	});
	
	//máscaras de formulário
	$.mask.options = {
		attr: 'alt', // an attr to look for the mask name or the mask itself
		mask: null, // the mask to be used on the input
		type: 'fixed', // the mask of this mask
		maxLength: 5000, // the maxLength of the mask
		defaultValue: '', // the default value for this input
		textAlign: true, // to use or not to use textAlign on the input
		selectCharsOnFocus: true, //selects characters on focus of the input
		setSize: true, // sets the input size based on the length of the mask (work with fixed and reverse masks only)
		autoTab: false, // auto focus the next form element
		fixedChars : '[(),.:/ -]', // fixed chars to be used on the masks.
		onInvalid : function(){},
		onValid : function(){},
		onOverflow : function(){}
	};
	$.mask.masks = {
		'ddd'     : { mask : '99' },
		'fone'     : { mask : '9999-9999' },
		'foneddd'     : { mask : '(99) 9999-9999' },
		'cpf'       : { mask : '999.999.999-99' },
		'data'      : { mask : '39/19/2999' },
		'cep'       : { mask : '99999-999' },
		'ano'      : { mask : '2999' }
	};
	$('input:text').setMask();

	/* PNGs */
	var badBrowser = (/MSIE ((5\.5)|6)/.test(navigator.userAgent) && navigator.platform == "Win32");
	if (badBrowser) $('img[src$=.png]').each(function() {
		if (!this.complete) this.onload = function() { fixPng(this) };
		else fixPng(this);
	});

	// Rollover das imagens
	$('.imghover').removeClass('produto').bind("mouseenter mouseleave",function(event) {
		$(this).stop(true).animate({ backgroundPosition: (event.type=='mouseenter'?'-'+$(this).width():0)+'px' }, 300);
	});

	//funcoes especificas das páginas
	//alert(myself.toLowerCase().replaceAll(' ','').replaceAll('-','')+'();');
	try { eval(myself.toLowerCase().replaceAll(' ','').replaceAll('-','')+'();') } catch(err) {};

	//
	login();
	
	extensoesJquery();
	
	// estampas
	$('#formEstampas').validate({
		rules: {
			titulo: {
				required: true
			},
			comentarios: {
				required: true
			},
			tags: {
				required: true
			},
			arquivo: {
				required: true,
				accept: "jpe?g"
			},
			arquivo2: {
				required: true,
				accept: "jpe?g"
			}
		},
		messages: {
			titulo: {
				required: "Este campo é requerido."
			},
			comentarios: {
				required: "Este campo é requerido."
			},
			tags: {
				required: "Este campo é requerido."
			},
			arquivo: {
				required: "Este campo é requerido.",
				accept: "Favor selecionar uma imagem JPG"
			},
			arquivo2: {
				required: "Este campo é requerido.",
				accept: "Favor selecionar uma imagem JPG"
			}
		}
	});
	
	$('#comentarEstampa form').validate({
		rules: {
			comentario: {
				required: true
			}
		},
		messages: {
			comentario: {
				required: "Este campo é requerido."
			}
		},
		submitHandler: function(form){
			$.ajax({
				url: 'envolva_se/vote/comentar.asp',
				data: 'comentario=' + escape($(form).find('textarea').val()) + '&id=' + $.query.get('id'),
				type: 'post',
				success: function(data){
					data = parseInt($.trim(data));
					switch (data) {
						case 1:
							$.ajax({
								url: 'envolva_se/vote/',
								data: 'id=' + $.query.get('id'),
								cache: false,
								success: function(data){
									$('.comentarios').html($('.comentarios',data).html())
									alert("Comentário inserido com sucesso");
								}
							});
						break;
						case -1:
							$.ajax({
								url: 'envolva_se/vote/',
								data: 'id=' + $.query.get('id'),
								cache: false,
								success: function(data){
									$('#login').html($('#login',data).html());
									login();
									alert("Sua sessão expirou. Faça login novamente para poder avaliar as estampas");
								}
							});
						break
						default:
							alert("Ocorreu um erro ao tentar salvar seu voto. Favor tentar novamente em alguns segundos");
					}
				}
			});
		}
	});
	
	$('.starBanca').rating({
		focus: function(value, link){
			$('#hoverstar').html(link.title || value);
		},
		blur: function(value, link){
			$('#hoverstar').html('');
		},
		callback: function(value, link){
			$.ajax({
				url: 'envolva_se/vote/votar.asp',
				data: 'id=' + $.query.get('id') + '&v=' + value,
				cache: false,
				success: function(data){
					data = parseInt($.trim(data));
					switch (data) {
						case 1:
							$.ajax({
								url: 'envolva_se/vote/',
								data: 'id=' + $.query.get('id'),
								cache: false,
								success: function(data){
									$('.avaliacao').html($('.avaliacao',data).html())
									$('.starBanca').rating();
								}
							});
						break
						case -1:
							$.ajax({
								url: 'envolva_se/vote/',
								data: 'id=' + $.query.get('id'),
								cache: false,
								success: function(data){
									$('#login').html($('#login',data).html());
									login();
									alert("Sua sessão expirou. Faça login novamente para poder avaliar as estampas");
								}
							});
						break
						case -2:
							alert("Você já votou nesta estampa");
						break
						default:
							alert("Ocorreu um erro ao tentar salvar seu voto. Favor tentar novamente em alguns segundos");
					}
				}
			});
		}
	});

	$('.avaliacao').show();

	$('#avise').validate({
		rules: {
			email: {
				email: true,
				required: true
			}
		},
		submitHandler: function(form){
			data = document.location.toString().substr(document.location.toString().indexOf('?')+1)
			$.ajax({
				url: 'loja/aviseme.asp',
				data: data + '&email=' + $(form).find('input[name="email"]').val(),
				success: function(data){
					alert("Sua solicitação foi gravada com sucesso.\n\nTão logo este produto esteja disponível, avisaremos pelo e-mail "+$(form).find('input[name="email"]').val()+".")
				}
			});
		}
	});
	
	$('a.indique').click(function(){
		$('#formEnviar').toggleClass('esconde');
	});
	
	$('#formEnviar form').validate({
		rules: {
			seuNome: {
				required: true
			},
			seuEmail: {
				email: true,
				required: true
			},
			nomeAmigo: {
				required: true
			},
			emailAmigo: {
				email: true,
				required: true
			}
		},
		submitHandler: function(form){
			data = document.location.toString().substr(document.location.toString().indexOf('?')+1)
			$.ajax({
				url: 'loja/indique.asp',
				data: data + '&dN=' + $(form).find('input[name="seuNome"]').val() + '&dE=' + $(form).find('input[name="seuEmail"]').val() + '&pN=' + $(form).find('input[name="nomeAmigo"]').val() + '&pE=' + $(form).find('input[name="emailAmigo"]').val(),
				success: function(data){
					alert("Sua solicitação foi gravada com sucesso.\n\nTão logo este produto esteja disponível, avisaremos pelo e-mail "+$(form).find('input[name="email"]').val()+".")
				}
			});
		}
	});
}

function login() {
	// login
	$('#login input').focus(function(){
		if($(this).attr('value') == $(this).attr('defaultValue')){
			$(this).attr('value','');
		}
	}).blur(function(){
		if($(this).attr('value') == ""){
			$(this).attr('value',$(this).attr('defaultValue'));
		}
	});
	$('#login form').validate({
		rules: {
			login: {
				required: true
			},
			senha: {
				required: true
			}
		},
		messages: {
			login: {
				required: " "
			},
			senha: {
				required: " "
			}
		},
		submitHandler: function(form) {
			$.ajax({
				url: 'login.asp',
				data: $(form).serialize(),
				type: 'post',
				cache: true,
				success: function(data){
					if ($.trim(data) == "true"){
						$.ajax({
							url: '/',
							cache: false,
							success: function(data){
								document.location = document.location;
							}
						})
					}else{
						alert("Login ou senha inválidos");
					}
				}
			})
		}
	});
}

function float2moeda(num) {
	var x = 0, ret;
	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 moeda2float(moeda){
	return parseFloat(moeda.replace('.','').replace(',','.'));
}

function calculaCarrinho(){
	var qt = 0;
	var vt = 0;
	$('#carrinho table tr.item').each(function(){
		q = parseInt($(this).find('input').val());
		if (q == 0) $(this).remove();
		qt += q;
		vu = moeda2float($(this).find('td.valorUn').html());
		vt += q * vu;
		$(this).find('td.totalUn').html(float2moeda(q * vu));
	});
	vt += moeda2float($('.frete').html());
	if (vt <= 100){
		$('#freteBox').show();
	}else{
		$('#freteBox').hide();
	}
	$('#sacola b a').html(qt);
	$('#carrinho table .total').html(float2moeda(vt));
	miniCarrinho();
}

function miniCarrinho(){
	$.ajax({
		url: 'loja/carrinho.asp',
		cache: false,
		success: function(data){
			$('#miniCarrinho table').html('');
			$('#sacola').mouseenter(function(){
				$('#miniCarrinho').stop(true,true).show('fast');
			}).mouseleave(function(){
				$('#miniCarrinho').hide('fast');
			});
			$('#carrinho table tr.alternada, #carrinho table tr.normal',data).each(function(){
				html = '<tr>'
				html += '<td width="60%">' + $(this).find('td:eq(1) span').html() + '</td>'
				html += '<td width="10%" class="center">' + $(this).find('td:eq(4) input').val() + '</td>'
				html += '<td width="30%" class="right">R$ ' + $(this).find('td:eq(6)').html() + '</td>'
				html += '</tr>'
				$('#miniCarrinho table').append(html);
			});
			html  = '<tr>'
			html += '<th colspan="2" width="70%"><b>Frete:</b></th>'
			html += '<th width="30%" class="right">R$ ' + $('#carrinho table th.frete',data).html() + '</th>'
			html += '</tr>'
			html += '<tr>'
			html += '<th colspan="2" width="70%"><b>Subtotal:</b></th>'
			html += '<th width="30%" class="right">R$ ' + $('#carrinho table th:last',data).html() + '</th>'
			html += '</tr>'
			$('#miniCarrinho table').append(html);
		}
	});
}

/* PNGs */
var blank = new Image();
blank.src = '/imgs/pix.gif';
function fixPng(png) {
	// get src
	var src = png.src;
	// set width and height
	if (!png.style.width) { png.style.width = $(png).width(); }
	if (!png.style.height) { png.style.height = $(png).height(); }
	// replace by blank image
	png.onload = function() { };
	png.src = blank.src;
	// set filter (display original image)
	png.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
}

//trabalhe conosco
function trabalheconosco() {
	$('#formTrabalhe').validate({
		rules: {
			nome: {
				required:true
			},
			civil: {
				required:true
			},
			data_nasc: {
				required:true,
				dateBR: true
			},
			endereco: {
				required:true
			},
			bairro: {
				required:true
			},
			cep: {
				required:true
			},
			cidade: {
				required:true
			},
			estado: {
				required:true
			},
			telefone: {
				required:true
			},
			celular: {
				required:true
			},
			email: {
				required:true,
				email:true
			},
			interesse: {
				required:true
			},
			escolar: {
				required:true
			},
			empresa1: {
			},
			admissao1: {
				dateBR: true
			},
			demissao1: {
				dateBR: true
			},
			funcoes1: {
			},
			empresa2: {
			},
			admissao2: {
				dateBR: true
			},
			demissao2: {
				dateBR: true
			},
			funcoes2: {
			},
			empresa3: {
			},
			admissao3: {
				dateBR: true
			},
			demissao3: {
				dateBR: true
			},
			funcoes3: {
			},
			idiomas: {
				required:true
			},
			computacao: {
				required:true
			},
			informacoes: {
			}
		}
	})
}
//modelo por um dia
function modelo() {
	$('#modelo').validate({
		rules: {
			nome: {
				required:true
			},
			email: {
				required:true,
				email:true
			},
			telefone: {
				required:true
			},
			file1: {
				required:true,
				accept: 'jpg|jpeg'
			}
		}
	})
}
//seja um franqueado
function sejaumfranqueado() {
	$('#franquias').validate({
		rules: {
			nome: {
				required:true
			},
			cpf: {
				required:true,
				cpf: true
			},
			data_nasc: {
				required:true,
				dateBR: true
			},
			endereco: {
				required:true
			},
			bairro: {
				required:true
			},
			cep: {
				required:true,
				minlenght: 9,
				maxlenght: 9
			},
			cidade: {
				required:true
			},
			estado: {
				required:true
			},
			telefone: {
				required:true,
				minlenght: 9,
				maxlenght: 9
			},
			celular: {
				required:true,
				minlenght: 9,
				maxlenght: 9
			},
			email: {
				required:true,
				email:true
			},
			capital: {
				required:true
			},
			regiao: {
				required:true,
				minlenght: 8
			}
		}
	})
}

//camisetas promocionais
function camisetaspromocionais() {
	var flashvars = {};
	var params = {};
	var attributes = {};
	
	swfobject.embedSWF("swf/camisetas_promocionais.swf", "flashCamisetas", "300", "463", "9.0.0","expressInstall.swf", flashvars, params, attributes);
}
//contato
function contato() {
	$('#contato').validate({
		rules: {
			nome: {
				required:true
			},
			email: {
				required:true,
				email:true
			},
			assunto: {
				required:true
			},
			mensagem: {
				required:true
			}
		}
	})
}

//contato
function estampas() {
	$('#estampas').validate({
		rules: {
			nome: {
				required:true
			},
			email: {
				required:true,
				email:true
			},
			arquivo: {
				required:true,
				accept: 'jpg|jpeg|png|gif'
			},
			mensagem: {
				required:true
			}
		}
	})
}

//cadastro
function cadastro() {
	$('#formCadastro').validate({
		rules: {
			nome: {
				required:true
			},
			cgccpf: {
				required:true,
				cpf:true
			},
			data_nasc: {
				required:true,
				dateBR: true
			},
			b_numero: {
				required:true,
				number: true
			},
			rua: {
				required:true
			},
			complemento: {
				required:true
			},
			bairro: {
				required:true
			},
			cep: {
				required:true,
				minlength: 9,
				maxlength: 9
			},
			cidade: {
				required:true
			},
			estado: {
				required:true
			},
			ddd: {
				required:true,
				minlength: 2,
				maxlength: 2,
				min: 10
			},
			telefone: {
				required:true,
				minlength: 9,
				maxlength: 9
			},
			email: {
				required:true,
				email:true
			},
			password: {
				required:true,
				minlength: 3
			},
			password2: {
				required:true,
				equalTo: '#password'
			}
		}
	})
}

function identificação(){
	$('#formIdent').validate({
		rules: {
			email: {
				required:true,
				email:true
			},
			senha: {
				required: '#tipo2:checked'
			}
		}
	});
}

//esqueci minha senha
function confirmarcadastro() {
	$('#formConfirmaCadastro').validate({
		rules: {
			b_nome: {
				required:true
			},
			cgccpf: {
				required:true,
				cpf:true
			},
			data_nasc: {
				required:true,
				dateBR: true
			},
			b_rua: {
				required:true
			},
			b_numero: {
				required:true,
				number: true
			},
			b_complemento: {
				required:true
			},
			b_bairro: {
				required:true
			},
			b_cep: {
				required:true,
				minlength: 9,
				maxlength: 9
			},
			b_cidade: {
				required:true
			},
			b_estado: {
				required:true
			},
			b_ddd_telefone: {
				required:true,
				minlength: 2,
				maxlength: 2,
				min: 10
			},
			telefone: {
				required:true,
				minlength: 9,
				maxlength: 9
			},
			email: {
				required:true,
				email:true
			},
			nome: {
				required:true
			},
			rua: {
				required:true
			},
			complemento: {
				required:true
			},
			bairro: {
				required:true
			},
			cep: {
				required:true,
				minlength: 9,
				maxlength: 9
			},
			cidade: {
				required:true
			},
			estado: {
				required:true
			},
			b_pais: {
				required:true
			},
			pais: {
				required:true
			}
		}
	})
}
//esqueci minha senha
function esqueciminhasenha() {
	$('#formEsqueci').validate();
}
//Onde comprar
function ondecomprar() {
	google.load('maps', '2.x', { 'other_params':'oe=iso-8859-1', 'callback': function() {
		function criaMarcador(ponto, texto) {
			var objIcone = new google.maps.Icon(G_DEFAULT_ICON);
			objIcone.shadow = "/site/imgs/mapShadow.png";
			objIcone.iconSize = new google.maps.Size(20, 34);
			objIcone.shadowSize = new google.maps.Size(37, 34);
			objIcone.iconAnchor = new google.maps.Point(9, 34);
			objIcone.infoWindowAnchor = new google.maps.Point(9, 2);
			objIcone.image = "/site/imgs/mapMarker.png";
		
			var objMarcador = new google.maps.Marker(ponto, { icon:objIcone });
		
			google.maps.Event.addListener(objMarcador, "click", function() {
				var objTexto = $('<div><span class="fonte1 fCor1">'+texto+'</span></div>');
				$('a',objTexto).replaceWith($('a',objTexto).html());
				$('b',objTexto).addClass('fCor3');
				objMarcador.openInfoWindowHtml(objTexto.html());
			});
			return objMarcador;
		}

		var map = new google.maps.Map2(document.getElementById('map'));

		var brasil = new google.maps.LatLng(-14.5, -54.3);
		map.setCenter(brasil, 4);
		map.setUIToDefault();

		//Mapa fixo na tela.
		var mapTopStart = $('#map').offset().top;
		$(window).scroll(function () {
			var conteudoHeight = $('#conteudo').innerHeight()-parseInt($('#conteudo').css('padding-top').replace('px',''))-parseInt($('#conteudo').css('padding-bottom').replace('px',''));
			if ($(window).scrollTop() < mapTopStart) $('#map').offset({ top: mapTopStart });
			else if ($(window).scrollTop() + $('#map').height() > $('#conteudo').offset().top + conteudoHeight)	$('#map').offset({ top: $('#conteudo').offset().top + conteudoHeight - $('#map').height() });
			else $('#map').offset({ top: $(window).scrollTop() });
		});
		
		// Adiciona os marcadores e o evento de click
		$('a[class*="lat:"]').each(function() {
			var marcador = criaMarcador(new google.maps.LatLng($(this).metadata().lat, $(this).metadata().lng),$(this).parent().html());
			map.addOverlay(marcador);
			$(this).click(function() { map.setCenter(marcador.getLatLng(), $(this).metadata().zoom); return false; });
		});
		//Recolhe os endereços
		$('#lojas h2').click(function() {
			$('#lojas h2').next().slideUp();
			if($(this).next().is(':hidden')) {
				$(this).next().slideDown();
				map.getInfoWindow().hide();
				map.setCenter(new google.maps.LatLng($(this).metadata().lat, $(this).metadata().lng), $(this).metadata().zoom);
			} else map.setCenter(brasil, 4);
		}).next().hide();
	}});
}


//tia mais
function riamais() {
	$('#marcas input:not(:eq(0)), #temas input:not(:eq(0)), #tamanhos input:not(:eq(0))').attr('disabled',true);
	$('#marcas input, #temas input, #tamanhos input').click(function(){
		pai = $(this).parent().parent();
		if(pai.find('input').index(this) == 0){
			// se marcar/desmarcar "todos"
			pai.find('input:not(:eq(0))').attr('disabled',this.checked);
			pai.find('input:not(:eq(0))').attr('checked',this.checked);
		}else{
			// se marcar/desmarcar todos os elementos
		}
	});
}

//loja online
function lojaonline() {
	// loja
	// telas inicial e de produtos
	$('.alterar').click(function(){
		processaAlteracaoCarrinho($(this).parents('td').find('input'));
	});
	$('.remover').click(function(){
		$(this).parents('tr').find('input').val(0);
		processaAlteracaoCarrinho($(this).parents('tr').find('input'));
	});
	$('#marcas input:not(:eq(0)), #temas input:not(:eq(0)), #tamanhos input:not(:eq(0))').attr('disabled',true);
	$('#marcas input, #temas input, #tamanhos input').click(function(){
		pai = $(this).parent().parent();
		if(pai.find('input').index(this) == 0){
			// se marcar/desmarcar "todos"
			pai.find('input:not(:eq(0))').attr('disabled',this.checked);
			pai.find('input:not(:eq(0))').attr('checked',this.checked);
		}else{
			// se marcar/desmarcar todos os elementos
		}
	});
	$('.tamanhos a').click(function(){
		$('.tamanhos a').removeClass('selecionado');
		$(this).addClass('selecionado');
		$('a.carrinho').attr('href','loja/adiciona_carrinho.asp?tam=' + $(this).metadata().t + '&quant=1&id=' + $(this).metadata().id);
	});
	// carrinho
	$('#carrinho tr.item input').blur(function(){
		processaAlteracaoCarrinho(this);
	});
	// carrinho
	$('#carrinho input[name="cep"]').blur(function(){
		calculaFrete();
	});
}

function processaAlteracaoCarrinho(el){
	q = 0;
	if ($(el).val() == "" || $(el).val() == "0") {
		$(el).val(0);
	}
	$.ajax({
		url: 'loja/adiciona_carrinho.asp',
		cache: false,
		data: 'i=0&tam=' + $(el).metadata().t + '&id='+ $(el).metadata().id + '&quant=' + $(el).val(),
		success: function(){
			calculaFrete();
		}
	})
}

function calculaFrete(){
	var qt=0;
	$('#carrinho table tr.item').each(function(){
		q = parseInt($(this).find('input').val());
		if (q == 0) $(this).remove();
		qt += q;
	});
	$.ajax({
		url: 'loja/frete.asp',
		cache: false,
		data: 'q='+qt+'&cep='+$('#carrinho input[name="cep"]').val(),
		success: function(data){
			$('.frete').html($.trim(data))
			calculaCarrinho();
		}
	})
}

function extensoesJquery(){
	jQuery.validator.addMethod("cpf", function(value, element, param) {
		value = value.replace('.','');
		value = value.replace('.','');
		cpf = value.replace('-','');
		if (!param) return true;
		if (cpf.length == 0) return true;
		while(cpf.length < 11) cpf = "0"+ cpf;
		var expReg = /^0+$|^1+$|^2+$|^3+$|^4+$|^5+$|^6+$|^7+$|^8+$|^9+$/;
		var a = [];
		var b = new Number;
		var c = 11;
		for (i=0; i<11; i++){
			a[i] = cpf.charAt(i);
			if (i < 9) b += (a[i] * --c);
		}
		if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
		b = 0;
		c = 11;
		for (y=0; y<10; y++) b += (a[y] * c--);
		if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
		if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10]) || cpf.match(expReg)) return false;
		return true;
	}, "Informe um CPF v&aacute;lido."); // Mensagem padrão 
	
	jQuery.validator.addMethod("dateBR", function(value, element, param) {
		//contando chars
		if (!param) return true;
		if (value.length == 0) return true;
		if(value.length!=10) return false;
		// verificando data
		var data 		= value;
		var dia 		= data.substr(0,2);
		var barra1		= data.substr(2,1);
		var mes 		= data.substr(3,2);
		var barra2		= data.substr(5,1);
		var ano 		= data.substr(6,4);
		if(data.length!=10||barra1!="/"||barra2!="/"||isNaN(dia)||isNaN(mes)||isNaN(ano)||dia>31||mes>12)return false;
		if((mes==4||mes==6||mes==9||mes==11) && dia==31)return false;
		if(mes==2  &&  (dia>29||(dia==29 && ano%4!=0)))return false;
		if(ano < 1900)return false;
		return true;
	}, "Informe uma data v&aacute;lida");  // Mensagem padrão 
	
	jQuery.validator.addMethod("dateTimeBR", function(value, element, param) {
		//contando chars
		if (!param) return true;
		if(value.length!=16) return false;
		// dividindo data e hora
		if(value.substr(10,1)!=' ') return false; // verificando se há espaço
		var arrOpcoes = value.split(' ');
		if(arrOpcoes.length!=2) return false; // verificando a divisão de data e hora
		// verificando data
		var data 		= arrOpcoes[0];
		var dia 		= data.substr(0,2);
		var barra1		= data.substr(2,1);
		var mes 		= data.substr(3,2);
		var barra2		= data.substr(5,1);
		var ano 		= data.substr(6,4);
		if(data.length!=10||barra1!="/"||barra2!="/"||isNaN(dia)||isNaN(mes)||isNaN(ano)||dia>31||mes>12)return false;
		if ((mes==4||mes==6||mes==9||mes==11) && dia==31)return false;
		if (mes==2  &&  (dia>29||(dia==29 && ano%4!=0)))return false;
		// verificando hora
		var horario 	= arrOpcoes[1];
		var	hora 		= horario.substr(0,2);
		var doispontos 	= horario.substr(2,1);
		var minuto 		= horario.substr(3,2);
		if(horario.length!=5||isNaN(hora)||isNaN(minuto)||hora>23||minuto>59||doispontos!=":")return false;
		return true;
	}, "Informe uma data e uma hora v&aacute;lida");	
	
	
	
	/*
	 *
	 * NOVO METODO PARA O JQUERY VALIDATE
	 * VALIDA CNPJ COM 14 OU 15 DIGITOS
	 * A VALIDAÇÃO É FEITA COM OU SEM OS CARACTERES SEPARADORES, PONTO, HIFEN, BARRA
	 *
	 * ESTE MÉTODO FOI ADAPTADO POR:
	 * 
	 * Shiguenori Suguiura Junior <junior@dothcom.net>
	 * 
	 * http://blog.shiguenori.com
	 * http://www.dothcom.net
	 * 
	 */
	jQuery.validator.addMethod("cnpj", function(cnpj, element, param) {
		// DEIXA APENAS OS NÚMEROS
		cnpj = cnpj.replace('/','');
		cnpj = cnpj.replace('.','');
		cnpj = cnpj.replace('.','');
		cnpj = cnpj.replace('-','');
		
		if (!param) return true;
		if (cnpj.length == 0) return true;
		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)){
				return false;
			}
			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 false;
			}
			return true;
		}else{
			return false;
		}
	}, "Informe um CNPJ v&aacute;lido."); // Mensagem padrão 
	
	jQuery.validator.addMethod("notEqual", function(value, element, param) {
		return value == $(param).val() ? false : true;
	}, "Este valor n&atilde;o pode ser igual"); // Mensagem padrão 
}