window.addEvent('domready', function() {
	if ($('frm2')) {
		$('botao').addEvent('click',function(e){
			var event = new Event(e);
			var frm = new acForm("frm2",false);
			if (frm.error) {
				event.stop();
				event.preventDefault();
				event.stopPropagation(); 
			}
		});
	}
	if ($('frm_res')) {
		$('bt_resposta').addEvent('click',function(e){
			var event = new Event(e);
			var frm = new acForm("frm_res",false);
			if (frm.error) {
				event.stop();
				event.preventDefault();
				event.stopPropagation(); 
			}
		});
	}
	if ($('frmLogin')) {
		$('btLogin').addEvent('click',function(e){
			var event = new Event(e);
			var frm = new acForm("frmLogin",true);
			if (frm.error) {
				event.stop();
				event.preventDefault();
				event.stopPropagation(); 
			}
		});
	}
	
	if ($('menos')) {
		$('qtdtxt').addEvent('keypress',function(e) {
			if (isNaN(e.key) == true && ['left','right','up','down','backspace','delete'].indexOf(e.key) < 0) e.stop();
			else if (['backspace','delete'].indexOf(e.key) >= 0 && this.get('value').toInt() <=1) e.stop();
		});
	
		$('menos').addEvent('click',function(e) {
			if ($('qtdtxt').get('value').toInt() <=1) e.stop();
			else $('qtdtxt').set('value',$('qtdtxt').get('value').toInt()-1);
			if ($('qtdtxt').get('value').toInt() == 1) {
				$(document.body).getElements('div[class=acacabamento]').each(function(el){
					id = el.getElement('span').getProperty('ac');
					valor = el.getElement('span').getProperty('ac1').replace(',','.');
					el.set('value',id+','+valor);
					el.getElement('span').set('html','R$ '+valor.replace('.',','));
				});
			} else {
				$(document.body).getElements('div[class=acacabamento]').each(function(el){
					id = el.getElement('span').getProperty('ac');
					qtd = $('qtdtxt').get('value');
					total2 = el.getElement('span').getProperty('ac2');
					total = total2.replace('.','');
					total = total.replace(',','.').toFloat();
					valor = String(total*qtd);
					numf = valor.indexOf('.');
					if (numf>=0) {
						num = valor.length-numf;
						if (num == 2) valor = valor+'0';
					}
					else valor = valor+'.00';
					el.getElement('input[type=checkbox]').set('value',id+','+valor);
					total2 = valor.replace('.',',')
					el.getElement('span').set('html','R$ '+total2);
				});
			}
		});
		$('mais').addEvent('click',function(e) {
			if ($('qtdtxt').get('value').toInt() < 10000) $('qtdtxt').set('value',$('qtdtxt').get('value').toInt()+1);
			if ($('qtdtxt').get('value').toInt() > 1) {
				$(document.body).getElements('div[class=acacabamento]').each(function(el){
					id = el.getElement('span').getProperty('ac');
					qtd = $('qtdtxt').get('value');
					total2 = el.getElement('span').getProperty('ac2');
					total = total2.replace('.','');
					total = total.replace(',','.').toFloat();
					valor = String(total*qtd);
					numf = valor.indexOf('.');
					if (numf>=0) {
						num = valor.length-numf;
						if (num == 2) valor = valor+'0';
					}
					else valor = valor+'.00';
					el.getElement('input[type=checkbox]').set('value',id+','+valor);
					total2 = valor.replace('.',',')
					el.getElement('span').set('html','R$ '+total2);
				});
			}
		});
	}	
});
function acObs(id,opc) {
	if (opc) { 
		$('acabamento'+id).setStyle('display','none'); 
		if ($('obs'+id).getStyle('display') != 'block') $('obs'+id).setStyle('display','block'); 
		else $('obs'+id).setStyle('display','none');
	}
	else {
		$('obs'+id).setStyle('display','none'); 
		if ($('acabamento'+id).getStyle('display') != 'block') $('acabamento'+id).setStyle('display','block'); 
		else $('acabamento'+id).setStyle('display','none');
	}
}
function acBusca(form) {
	if (!$('txt_busca').get('value')) {
		acError('acErro5','');
		return false;
	}
}
function acAviso(msg) {
	acBgAlert();
	var acBoxMsg = new Element('div', {'id':'acalertbox'})
		.set("html",msg+"<br/><img src='img/load.gif' />")
		.setStyles({
			height: 60,
			width: 400,
			align: 'center',
			position: 'absolute',
			'z-index': '1000',
			opacity: 1,
			color: '#000',
			top: (window.getCoordinates().bottom/2)-35,
			left: (window.getCoordinates().right/2)-205
		})
		.injectInside(document.body);
}
function acBgAlert() {
	if (Browser.Engine.name == 'trident' && Browser.Engine.version < 5) ie6 = true;
	else ie6 = false;
	
	var formtags = $$('select','textarea');
	if ($('acalert')) {
		$(document.body).getElements('*[id^=acalert]').dispose();
		if (ie6 && formtags) formtags.setStyle('visibility', 'visible');
	}
	else {
		if (formtags.length > 0 && ie6) formtags.setStyle('visibility', 'hidden');
		var acBox = new Element('div', {"id":"acalert"})
			.setStyles({
				opacity: 0.7,
				background: '#000',
				position: 'absolute',
				top: 0,
				left: 0,
				width: window.getScrollSize().x,
				height: window.getScrollSize().y
			})
			.injectInside(document.body);
	}
	$(document.body).scrollTo(0,0);
}
function acDesAviso() {
	if ($('acalertbox')) $('acalertbox').dispose();
	acBgAlert();
}
function acError(msg,camp) {
	acBgAlert();
	var txt;
	if (msg.contains('acErro0')) {
		txt = "Você não está logado ou sua sessão expirou.";
	}
	if (msg.contains('acErro1')) {
		campo = camp.substring(camp.indexOf("="));
		txt = "Este "+camp+" já está sendo utilizado, favor tentar um diferente."
	}
	if (msg.contains('acErro2')) {
		campo = camp.substring(camp.indexOf("="));
		txt = "O campo "+camp+" deve ser preenchido."
	}
	if (msg.contains('acErro3')) {
		txt = "Dado não encontrado no sistema."
	}
	if (msg.contains('acErro4')) {
		txt = "Favor preencher com algum texto para a busca."
	}
	if (msg.contains('acErro5')) {
		txt = "A sessão expirou favor reenviar os seus dados."
	}
	if (msg.contains('acErro100')) {
		txt = "Erro de sistema, favor contactar a administração."
	}
	if (!txt) txt = msg;
	var acBoxMsg = new Element('div', {'id':'acalertbox'})
		.set("html",txt+"<br/><input type='button' id='alertsim' value='Ok'/>")
		.setStyles({
			height: 60,
			width: 400,
			align: 'center',
			position: 'absolute',
			'z-index': '1000',
			opacity: 1,
			color: '#000',
			top: (window.getCoordinates().bottom/2)-35,
			left: (window.getCoordinates().right/2)-205
		})
		.injectInside(document.body);
	$('alertsim').addEvent('click',function(){
		acBgAlert();
		if (msg.contains('acErro0')) document.location='login.asp';
	});
	$('acalert').addEvent('click',function(){
		acBgAlert()
		if (msg.contains('acErro0')) document.location='login.asp';
	});
}

function acMoeda(valor) {
	numf = '';
	num = '';
	texto = '';
	numf = valor.indexOf(',');
		
	if (numf>=0) {
		num = valor.length-numf;
		if (num == 2) texto = valor+'0';
	}
	else texto = valor+',00';
	return texto;
}
function acUp(tipo,id,produto,recebe,pedido) {
	acBgAlert();
	var acBord = new Element('img', {'src':'img/brd-top.gif', 'id':'brdAlert1'})
	.setStyles({height: 10,width: 300,position: 'absolute','z-index': 1000,top: (window.getCoordinates().bottom/2)-50,left: (window.getCoordinates().right/2)-150})
	.injectInside(document.body);
	var acBord2 = new Element('img', {'src':'img/brd-bot.gif', 'id':'brdAlert2'})
	.setStyles({height: 10,width: 300,position: 'absolute','z-index': 1000,top: (window.getCoordinates().bottom/2)+55,left: (window.getCoordinates().right/2)-150})
	.injectInside(document.body);
	var acBt = new Element('div', {'id':'bts'})
	.set("html","<center><input type='button' value='fechar' class='bt77' id='btsim' /></center>")
	.setStyles({height: 20,width: 250,position: 'absolute','z-index': 1200,top: (window.getCoordinates().bottom/2)+40,left: (window.getCoordinates().right/2)-125})
	.injectInside(document.body);
	$('btsim').addEvent('click',function(){
		acBtSim(false,false);
	});
	var acBoxMsg = new IFrame({
		
	src: 'imagem.asp?tipo='+tipo+'&id='+id+'&produto='+produto+'&recebe='+recebe+'&pedido='+pedido,
			id: 'aciframe',
			'scrolling': "no",
			'frameborder': 0,
			styles: {
				width: 300,
				height: 100,
				opacity: 1,
				border: 'none',
				background: '#fff',
				position: 'absolute',
				'z-index': 1000,
				align: 'center',
				top: (window.getCoordinates().bottom/2)-45,
				left: (window.getCoordinates().right/2)-150
			}
		})
		.injectInside(document.body);
}
function acBtSim(rel,recebe) {
	acBgAlert();
	$('btsim').destroy();
	$('brdAlert1').destroy();
	$('brdAlert2').destroy();
	$('aciframe').destroy();
	if (recebe) $(recebe).set('html','Arquivo enviado com sucesso!');
	if (rel) window.location.reload();
}
function acMsg(msg) {
	acBgAlert();
	var acBoxMsg = new Element('div', {'id':'acalertbox'})
		.set("html",msg+"<br/><input type='button' id='acalertsim' value='Ok'/>")
		.setStyles({
			width: 400,
			align: 'center',
			position: 'absolute',
			'z-index': '1000',
			opacity: 0,
			color: '#000',
			left: (window.getCoordinates().right/2)-205
		})
		.injectInside(document.body);
		$('acalertbox').setStyle('top',(window.getCoordinates().bottom/2)-($('acalertbox').getSize().y/2)-5)
		var myFx = new Fx.Tween('acalertbox');
		myFx.start('opacity', '0', '1');
		if (!$('acalert')) acBgAlert();
		$('acalertsim').addEvent('click',function(){acBgAlert();});
		$('acalert').addEvent('click',function(){acBgAlert()});
}

var acForm = new Class({
	initialize: function(form,msg){
		if ($('erroForm')) $('erroForm').destroy();
		if ($('erroForm2')) $('erroForm2').destroy();
		if ($('erroForm3')) $('erroForm3').destroy();
		if ($('erroForm4')) $('erroForm4').destroy();
		var error = false;
		var status;
		$(form).getElements('*[class*=acObg]').each(function(el){
			status = true;
			if (el.getProperty('type') == 'checkbox' && !el.getProperty('checked')) status = false;
			else if (!el.get('value')) status = false;
			else if(el.get('acTipo') == 'email' && !el.get('value').match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+.[a-zA-Z0-9._-]+)/gi)){
				if (msg){
					var acBoxMsg = new Element('div', {'id':'erroForm2'})
					.set("html","E-mail inválido. Favor tentar mais uma vez.")
					.inject($(form),'before');
				}
				status = false;
				this.error = true;
				$(document.body).scrollTo(0,0);
			}
			else if(el.get('acTipo') == 'confirma_senha' && $('senha').get('value') != el.get('value')){
				if (msg){
					var acBoxMsg = new Element('div', {'id':'erroForm2'})
					.set("html","As senhas digitadas não conferem. Favor tentar mais uma vez.")
					.inject($(form),'before');
				}
				status = false;
				this.error = true;
				$(document.body).scrollTo(0,0);
			}
			else if (el.get('acTipo') == 'cpf'){
				 var cpf = el.get('value');
				 var cpferro = false;
                 if (cpf.length < 11) cpferro = true;
                 else {
					 var nonNumbers = /\D/;
		             if (nonNumbers.test(cpf)) cpferro = true;
			         if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999") cpferro = true;
				}
				if (!cpferro) {
					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])){
                       cpferro = true;
		             }
				} 
               if (cpferro) { 
				   if (msg){
					 var acBoxMsg = new Element('div', {'id':'erroForm3'})
					.set("html","CPF inválido. Favor tentar mais uma vez.")
					.inject($(form),'before');
				   }
					status = false;
					this.error = true;
					$(document.body).scrollTo(0,0);
				}
			}
			if (!status) {
				error = true;
				if (el.getPrevious()) el.getPrevious().setStyle('color','red');
				else if (el.getNext()) el.getNext().setStyle('color','red');
				el.setStyle('border','1px solid red');
			} else {
				if (el.getPrevious()) el.getPrevious().setStyle('color','#6F6F6F');
				else if (el.getNext()) el.getNext().setStyle('color','#6F6F6F');
				el.setStyles({'border':'1px outset #434343','background':'#fff'});
				el.set('value',el.get('value').clean());	
			}
		});
		if (error) {
			if (msg){
			var acBoxMsg = new Element('div', {'id':'erroForm'})
			.set("html","Por favor, complete os dados que faltam.")
			.inject($(form),'before');
			}
			this.error = true;
			$(document.body).scrollTo(0,0);
		} 
		else this.error = false;
	}
});
function acLimpaCep(el) {
	el.setStyles({'border':'1px outset #434343','background':'#fff'});
	el.setProperty('acValido','neutro')
}
function acTestCep(el) {
	var objER = /^[0-9]{2}[0-9]{3}[0-9]{3}$/;
	var strCEP = el.get('value').clean();
	if (el.get('value') && el.getProperty('acValido') == 'neutro' && objER.test(strCEP)) {
		el.set('readonly',true);
		var acTt = new Element('img', {'id':'acTest','src':'img/test.gif'}).inject(el,'after');
		var jsonRequest = new Request.JSON({url: "includes/recebe_cep.asp?cep="+el.get('value'), 
			onComplete: function(json){
				if (!json || json.acCep[0].acerro == 1) {
					if ($('Bairro')) $('Bairro').set('value','');
					if ($('Cidade')) $('Cidade').set('value','');
					if ($('Estado')) $('Estado').set('value','');
					el.setStyles({'border':'1px outset red','background':'#FFDFDF'});
					el.set('readonly',false);
					el.setProperty('acValido','falso')
					$('acTest').dispose();
					return false;
				}
				else {						
					if ($('Bairro')) $('Bairro').set('value',json.acCep[0].bairro);
					if ($('Cidade')) $('Cidade').set('value',json.acCep[0].cidade);
					if ($('Estado')) $('Estado').set('value',json.acCep[0].estado);
					el.setStyles({'border':'1px outset #008000','background':'#ECFFEC'});
					el.setProperty('acValido','ok')
					el.set('readonly',false);
					$('acTest').dispose();
					return true;
				}
			}
		}).send();
	} else if (el.getProperty('acValido') == 'ok' && objER.test(strCEP)) return true;
	else { 
		if ($('Bairro')) $('Bairro').set('value','');
		if ($('Cidade')) $('Cidade').set('value','');
		if ($('Estado')) $('Estado').set('value','');
		el.setStyles({'border':'1px outset red','background':'#FFDFDF'});
		el.set('readonly',false);
		el.setProperty('acValido','falso')
		return false;
	}
}
function acDelProduto(id){
	var acPagina = 'carrinho.asp?acao=Remover&produto='+id;
	acAviso('Excluindo produto...');	
	var ajax = new Request({url:acPagina,
		onSuccess: function(html) {
			acDesAviso();
			if (html.contains('ok=1')) {
				window.location.reload();
			} else {
				var acBoxMsg = new Element('div', {'id':'divOK'})
				.set('html','<p class="erro">Erro no sistema, o produto não foi removido.</p>')
				.inject($('listaProdutos'),'before');
			}
		},
		onFailure: function(html) {
			acDesAviso();
			var acBoxMsg = new Element('div', {'id':'divOK'})
			.set('html','<p class="erro">Erro no sistema, o produto não foi removido.</p>')
			.inject($('listaProdutos'),'before');
		}		
	}).send();
}
function acNum(event) {
	event = new Event(event);
	var validKeys = ['shift','backspace','left','up','down','right','tab','#','$','1','2','3','4','5','6','7','8','9','0'];
	if (!validKeys.contains(event.key)) {
		event.stop();
		event.preventDefault();
		event.stopPropagation(); 
	}
}