// JavaScript Document
function w(div_name){
	return document.getElementById(div_name);
}

function getDataForm(fields, labels){
	for(i=0 ; i<fields.length ; i++){
		if( w(fields[i]).value == '' ){
			alert('Preencha o campo '+labels[i]+'!');
			w(fields[i]).focus();
			return false;
		}
	}
	return true;
}

document.gambi = "";

function checkMail(mail){
    var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
    if(typeof(mail) == "string"){
        if(er.test(mail)){ return true; }
    }else if(typeof(mail) == "object"){
        if(er.test(mail.value)){
                    return true;
                }
    }else{
        return false;
        }
}

window.onload = this.jsInit = function(){
	
	try{
		eval(document.gambi);
	}catch(e){
	}
	
	
	//self.resizeTo(screen.availWidth,screen.availHeight);
	
	if(w('form_contato')){
		w('form_contato').onsubmit = function(){
			var fields = new Array('nome' , 'cidade' , 'estado' , 'telefone' , 'email' , 'msg');
			var labels = new Array('Nome' , 'Cidade' , 'Estado' , 'Telefone' , 'E-mail' , 'Mensagem');
			w('form_contato').onsubmit = function(){
				return getDataForm(fields, labels);
			}
		}
	}
	
	if(w('cadastro')){
		mask('A1_DTNASC' , date);
		mask('A1_CGC' , numbers);
		mask('A1_CEP' , numbers);
		mask('A1_CEPC' , numbers);
		mask('A1_FAX' , phone);
		mask('A1_TEL' , phone);
		mask('A1_RG', numbers);
		mask('A1_INSCR', numbers);
		
		
		
		w('cadastro').onsubmit = function(){
			var f = new wForm('cadastro');
			var fields = new Array('A1_NOME' , 'A1_EMAIL' , 'A1_SENHA' , 'confirm' , 'A1_CEP' , 'A1_END' , 'A1_TEL', 'A1_FAX' , 'A1_BAIRRO' , 'A1_MUN' , 'A1_EST' , 'A1_CEPC' , 'A1_ENDCOB' , 'A1_BAIRROC' , 'A1_MUNC' , 'A1_ESTC');
			var labels = new Array('Nome/Razão Social' , 'E-mail' , 'Senha' , 'Confirmação de Senha' , 'CEP' , 'Endereço' , 'Telefone' , 'Fax' , 'Bairro' , 'Cidade' , 'Estado' , 'CEP de cobrança' , 'Endereço de cobrança' , 'Bairro de cobrança' , 'Município de Cobrança' , 'Estado de cobrança');
			
			if(!f.valida(fields, labels)){				
				return false;
			}
			
			if(!checkMail(w('A1_EMAIL').value))
			{
				w('A1_EMAIL').focus();
				alert('E-mail inválido!');
				return false;
			}
			
			if(w('A1_SENHA').value!=w('confirm').value){
				alert('A senha e sua confirmação não conferem!');
				return false;
			}
			
			if(w('PF').checked){
				var fields = new Array('A1_CGC' , 'A1_RG' , 'A1_DTNASC');
				var labels = new Array('CPF' , 'RG' , 'Data de Nascimento');
				mask('A1_CGC' , cpf);
				if(!validaCPF('A1_CGC')){
					return false;
				}
			}else if(w('PJ').checked){
				var fields = new Array('A1_CGC' , 'A1_INSCR');
				var labels = new Array('CNPJ' , 'Inscrição Estadual');
				mask('A1_CGC' , cnpj);
				if(!validaCNPJ('A1_CGC')){
					return false;
				}
			}
			
			if(!f.valida(fields, labels)){
				return false;
			}
		}
	}
	
	if(w('search_carrinho')){
		w('search_carrinho').onfocus = function(){
			this.value = "";
		}
		w('search_carrinho_ok').onclick  = function(){
		   if(w('search_carrinho').value!="" && w('search_carrinho').value!="Pesquisar"){
				w('div_carrinho').innerHTML = ajax.loadResult('carrinho_ajax.php?param='+w('search_carrinho').value);
		   }else{
				w('search_carrinho').focus();
		   }
			return false;
		}
	}
}

function pf(){
	w('nome_rsocial').innerHTML = 'Nome Completo';
	w('cpf_cnpj').innerHTML = 'CPF';
	//w('rg_ie').innerHTML = 'RG';
	w('A1_INSCR').disabled = true;
	w('A1_INSCR').value = '';
	w('A1_RG').disabled = false;
	w('A1_DTNASC').disabled = false;
}
function pj(){
	w('nome_rsocial').innerHTML = 'Razão Social';
	w('cpf_cnpj').innerHTML = 'CNPJ';
	//w('rg_ie').innerHTML = 'IE';
	w('A1_INSCR').disabled = false;
	w('A1_RG').value = '';
	w('A1_RG').disabled = true;
	//
	w('A1_DTNASC').disabled = true;
	w('A1_DTNASC').value = '';
}

function popup(lnk){
	var width = 500;
	var height = 550;
	
	var left = (screen.width - width)/2;
    var top = (screen.height - height)/2;

	window.open(lnk , 'popup', 'width='+width+', height='+height+', top='+top+', left='+left+', scrollbars=yes, status=no, toolbar=no, location=no, directories=no, menubar=no, resizable=no, fullscreen=no');
}

function adicionar(idd){
	var str = "<div class='Aadicionar' id='"+idd+"'><form name='ffr'><input type=\"image\" src=\"files/b2c/adicionar.gif\" onClick=\"if(document.getElementById('"+idd+"').getElementsByTagName('div')[0].style.display=='block'){fadeOut(document.getElementById('"+idd+"').getElementsByTagName('div')[0],true)}else{fadeIn(document.getElementById('"+idd+"').getElementsByTagName('div')[0],true)} this.blur(); return false;\"><div class=\"Abg\"><table width=\"100\" align=\"center\" cellspacing=\"2\"><tr><td colspan=\"2\" align=\"left\">Quantidade</td></tr><tr><td><input type=\"text\" name='"+idd+"_qtd' id='"+idd+"_qtd' value=\"1\" class=\"textfield\"></td><td><input type=\"image\" name=\"textfield\" id=\"textfield\" src=\"files/b2c/ok.gif\" onclick=\"add(document.getElementById('"+idd+"_qtd').value , '"+idd+"'); fadeOut(document.getElementById('"+idd+"').getElementsByTagName('div')[0] , true); return false;\"></td></tr></table></div><form></div>";
	document.write(str);
}

function add(qtd, id){
	try{
		if(eval(ajax.loadResult('addProduto.php?id='+id+'&qtd='+qtd))){
			welcome("Produto adicionado! visualize <a href='?l=16'>aqui</a>!");
		}else{
			alert('Você precisa estar logado para realizar esta operação.');
			welcome('<a href="?l=22">Clique aqui</a> para fazer o login.');
		}
	}catch(e){
		alert('Ocorreu um problema durante a operação, contate o suporte técnico!');
		alert(e.message)
	}
}


function download(idd){
	window.open('download.php?id='+idd , 'popup', 'width=100, height=100, top=100, left=100, scrollbars=no, status=no, toolbar=no, location=no, directories=no, menubar=no, resizable=no, fullscreen=no');
}

function welcome(msg){
	document.getElementById('mess').innerHTML = msg;
	document.getElementById('not').style.display = 'block';
	document.getElementById('mess').innerHTML = msg;
	try{
		clearTimeout(document.logado);
	}catch(e){}
	document.logado = setTimeout(
	   function(){
			document.getElementById('not').style.display = 'none';
	   }, 6000);
}

function editCarrinho(){
	welcome('Valide as alterações clicando em Salvar');
	w('salvar').disabled = false;
	w('carrinhoCR').action = 'alterarCarrinho.php';	
}

function salvarCarrinho(){
	if(send('carrinhoCR')){
		w('div_carrinho').innerHTML = ajax.loadResult('carrinho_ajax.php?rs=');
		welcome('Alterações salvas com sucesso!');
		w('salvar').disabled = true;
	}else{
		alert('Erro ao salvar, contate o suporte técnico!');
	}
}

function efetuarPedido()
{
	ajax.method = 'POST';
	var resp = ajax.loadResult('validaCarrinho.php?param=');	
	
	if(resp == 'true')
	{
		w('carrinhoCR').action = '?l=19';
		w('carrinhoCR').submit();
	} else {
		alert('Carrinho de compras está vazio.')
	}
	
}

this.showLoading = function(){
	try{
		w('wloading').style.display = 'block';
	}catch(e){}
}
this.hidLoading = function(){
	try{
		w('wloading').style.display = 'none';
	}catch(e){}
}

function sSearch(obj_param , obj_hid , obj_select){
	if(w(obj_param).value == '')
	{
		alert('Ditite algum valor');
		w(obj_param).focus();
	} else {
		w(obj_select).disabled = true;
		var res = ajax.loadResult('busca_campo.php?q=1&param='+w(obj_param).value);
		select_add(obj_select , res);
		w(obj_select).disabled = false;
	}
}

function validaFrete(valor)
{
	var resp = ajax.loadResult('get_frete.php?idEst='+valor);
	w('texto_frete').style.color = '#737373';
	
	if(resp == 'false')
	{
		w('id_estado_frete').selectedIndex = 0;
	}
	else
		w('calculo_frete').innerHTML = resp;
}

function valueRadio(name)
{
	var objs = document.getElementsByName(name);
	var aux = false;
	
	for(i=0; i < objs.length; i++)
	{
		if(objs[i].checked == true)
			aux = true;
	}
	
	return aux;
}

function validaFormPedido()
{
	if(w('id_estado_frete').value == 0)
	{
		alert('Selecione o estado de entrega do pedido');
		w('id_estado_frete').focus();
		w('texto_frete').style.color = 'red';
		return false;
	} else {
		w('texto_frete').style.color = '#737373';
	}
	
	if(!valueRadio('C5_IDZZF'))
	{
		alert('Selecione o método de pagamento');
		w('texto_metodo').style.color = 'red';
		return false;
	} else {
		w('texto_metodo').style.color = '#737373';
		
		if(!valueRadio('C5_CONDPAG'))
		{
			alert('Selecione a condição de pagamento');
			w('texto_parcelamento').style.color = 'red';
			return false;
		} else {
			w('texto_parcelamento').style.color = '#737373';
		}	

		
	}

	var campos = Array('A1_CEPC','A1_END','A1_BAIRRO','A1_MUN')
	var labels = Array('CEP', 'Endereço','Bairro','Cidade');
	
	for(i=0; i < campos.length; i++)
	{
		
		if(w(campos[i]).value == '')
		{
			alert('O campo '+labels[i]+' está inválido');
			w(campos[i]).focus();
			
			return false;
		}
	}
		
	w('form_pedidos').submit();
	
	// Validando os Campos

}

function getMetodoPag(obj)
{

	ajax.method = 'POST';
	w('texto_metodo').style.color = '#737373';
	
	var resp = ajax.loadResult('lista_pagamentos.php?idM='+obj.value);
	
	w('div_formas_pagamamentos').innerHTML = resp;
}

function buscaCep()
{
	   var width = 360;
	   var height = 380;
	   var left = (screen.width - width)/2;
	   var top = (screen.height - height)/2;;   
	   window.open('busca_cep.php','cep', 'width='+width+', height='+height+', top='+top+', left='+left+', scrollbars=no, status=no, toolbar=no, location=no, directories=no, menubar=no, resizable=no, fullscreen=no');
}

function geraBoleto(num_pedido)
{
	   var width = screen.width;
	   var height = screen.height;
	   var left = (screen.width - width)/2;
	   var top = (screen.height - height)/2;;   
	   window.open('../files/gera_boleto.php',num_pedido);
}
function abreAtendimento () {
	   var width = 450;
	   var height = 465;
	   var left = (screen.width - width)/2;
	   var top = (screen.height - height)/2;;   
	   window.open('../atd/view/?action=AppUsr/login','atendimento', 'width='+width+', height='+height+', top='+top+', left='+left+', scrollbars=no, status=no, toolbar=no, location=no, directories=no, menubar=no, resizable=no, fullscreen=no');
}


//valida os campos em branco de um formulario

this.valida = function(f, l){
	for(i=0 ; i<f.length ; i++){
		switch(w(f[i]).type){
			case 'select-one':
			
				if(w(f[i]).options[w(f[i]).selectedIndex].value == "nulo"){
					alert('Selecione uma opçao em '+l[i]+'!');
					return false;
				}
			break;
			
			case 'textarea':
			case 'password':
			case 'hidden':
			case 'text':
			if(w(f[i]).value == ''){
				alert('Preencha o campo '+l[i]+'!');
				w(f[i]).focus();
				return false;
			}

			break;
		}
	}
	return true;
}
var ajax = new Ajax();
ajax.method = 'POST';
ajax.assincr = false;


/*
* INIT
*/

var J = jQuery.noConflict();
/*
Object.prototype.merge = function(object){  }
Function.prototype.bind = function() { }
*/
function montaMenu( pos ) {

	var menuLeft = 'files/menu/menu_left';
	var menuRight = 'files/menu/menu_right';
	
	// Monta o menu
	var menuSite = J('#inf-topo li');

	for(var i=0; i < menuSite.length; i++) {
		
		J(menuSite[i]).mouseover(
			function() {
				var imgL = J('#' + this.id + ' img.left');
				var imgR = J('#' + this.id + ' img.right');
				
				J(imgL).attr('src', menuLeft  + '_over.gif');
				J(imgR).attr('src', menuRight + '_over.gif');
				
				J(this).attr('class', 'menu-over');
			}			
		);

		J(menuSite[i]).mouseout(
			function() {
				var l = this.id.split('_');
				if(l[1] != pos) {
					var imgL = J(this).find('.left');
					var imgR = J(this).find('.right');
					
					J(imgL).attr('src', menuLeft  + '.gif');
					J(imgR).attr('src', menuRight + '.gif');
					
					J(this).removeAttr('class');
				}
			}
		);
		
		J(menuSite[i]).click(
			function() {
				var l = this.id.split('_');
				window.location = '?l=' + l[1];
			}
		);
	}
}
