function validaVat (numero, isCNPJ)
{
    numero = numero.replace(/([^0-9])/g, '');
    if (isCNPJ)
    {
        return validateCnpj(numero);
    }
    else
    {
        return validateCpf(numero);
    }
}

function validateCpf (numero)
{
    if (numero.length != 11)
    {
        return false;
    }
    
    var i;
    var c = numero.substr(0,9);
    var dv = numero.substr(9,2);
    var d1 = 0;
    
    for (i = 0; i < 9; i++)
    {
        d1 += c.charAt(i)*(10-i);
    }

    if (d1 == 0)
    {
        return false;
    }

    d1 = 11 - (d1 % 11);

    if (d1 > 9)
    {
        d1 = 0;
    }

    if (dv.charAt(0) != d1)
    {
        return false;
    }

    d1 *= 2;

    for (i = 0; i < 9; i++)
    {
        d1 += c.charAt(i)*(11-i);
    }

    d1 = 11 - (d1 % 11);
    if (d1 > 9)
    {
        d1 = 0;
    }

    if (dv.charAt(1) != d1)
    {
        return false;
    }

    return true;
}

function validateCnpj (numero)
{
    if (numero.length != 14 && numero.length != 15)
    {
        return false;
    }

    if (numero.length == 15)
    {
        if (numero[0] != '0')
        {
            return false;
        }
        numero = numero.substr(1, 14);
    }

    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] = numero.charAt(i);
        b += a[i] * c[i+1];
    }

    x = b % 11;
    if (x < 2)
    {
        a[12] = 0;
    }
    else
    {
        a[12] = 11 - x;
    }
    
    b = 0;
    
    for (y = 0; y < 13; y++)
    {
        b += (a[y] * c[y]);
    }
    
    x = b % 11
    if (x < 2)
    {
        a[13] = 0;
    }
    else
    {
        a[13] = 11 - x;
    }
    
    if ((numero.charAt(12) != a[12]) || (numero.charAt(13) != a[13]))
    {
        return false;
    }

    return true;
}

function showPFFields()
{
	document.getElementById('informacoes_empresa').style.display = 'none';
	document.getElementById('label_taxvat').innerHTML = 'CPF <em>*</em> ';
}

function showPJFields()
{
	document.getElementById('informacoes_empresa').style.display = 'block';
	document.getElementById('label_taxvat').innerHTML = 'CNPJ <em>*</em> ';
}

/**
 * By Officeprev
 */
function mascaraData(elemento, evento)
{
    var chare = mascaraNoChar(evento);
    var tecla = typeof window.event != "undefined" ? window.event.keyCode : evento.which;

    if(chare){

        var data = elemento.value;

        if ((data.length == 2 || data.length == 5) && tecla != 8){  // se o proximo caractere for "/" insere automático. A não ser que seja backspace.
            data = data + "/";
            elemento.value = data;
        }

        if((tecla == 0) || (tecla == 8))
            return true;

        if(data.length == 10  && tecla != 8)
            return false;

        return true;
    }
    else
        return false;

}

/**
 * By Officeprev
 */
function mascaraNoChar(valor)
{
    var e = valor;

    if (window.event)
        var tecla = e.keyCode;

    else if(e.which)
        var tecla = e.which;

    if ( tecla < 48 || tecla > 57 )
    {
        if( tecla == 8 )
            return true;

        return false;
    }
    else
        return true;
}

/**
 * By Videoffice
 */
function keypress(e)
{
	var x = '';
	if (document.all)
	{
		var evnt = window.event;
		x = evnt.keyCode;
	}
	else
	{
		x = e.keyCode;
	}
	return x;
}

/**
 * By Videoffice
 */
function Limpar(valor, validos)
{
	// retira caracteres invalidos da string
	if( typeof valor != 'string' )
	{
		valor += '';
	}
	var result = "";
	var aux;
	for (var i=0; i < valor.length; i++) {
		aux = validos.indexOf(valor.substring(i, i+1));
		if (aux>=0) {
			result += valor.substring(i, i+1);
		}
	}
	return result;
}

/**
 * By Videoffice
 */
//Formata número tipo moeda usando o evento onKeyUp
function formataMoeda(campo, event, negativo)
{
	var tecla = keypress(event);

	if(negativo == true)
	{
		aceita = "-0123456789";
	}
	else
	{
		aceita = "0123456789";
	}

	vr  = Limpar(campo.value, aceita);
	tam = vr.length;
	dec = 2;

	if (tam < 18 && tecla != 8)
	{
		tam = vr.length;
	}

	campo.value = vr ;

	if ( (tam <= dec) && (tam > 0) )
	{
		campo.value = "," + vr.substr( tam - dec, tam ) ;
	}
	if ( (tam > dec) && (tam <= 5) )
	{
		campo.value = vr.substr( 0, tam - 2 ) + "," + vr.substr( tam - dec, tam ) ;
	}
	if ( (tam >= 6) && (tam <= 8) )
	{
		campo.value = vr.substr( 0, tam - 5 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ;
	}
	if ( (tam >= 9) && (tam <= 11) )
	{
		campo.value = vr.substr( 0, tam - 8 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ;
	}
	if ( (tam >= 12) && (tam <= 14) )
	{
		campo.value = vr.substr( 0, tam - 11 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ;
	}
	if ( (tam >= 15) && (tam <= 17) )
	{
		campo.value = vr.substr( 0, tam - 14 ) + "." + vr.substr( tam - 14, 3 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - 2, tam ) ;
	}
}

// Validações utilizando a estrutura do Magento
Validation.addAllThese([
	// CEP
    ['validate-cep', 'Por favor, insira um cep válido. Por exemplo 99999-999.', function(v,elm) {
        return Validation.get('IsEmpty').test(v) || /(^\d{5}-\d{3}$)/.test(v);
    }],
	// Telefone
    ['validate-fone', 'Por favor, insira um número válido. Por exemplo (99) 9999-9999.', function(v,elm) {
        return Validation.get('IsEmpty').test(v) || /^(\()?\d{2}(\))?(-|\s)?\d{4}(-|\s)\d{4}$/.test(v);
    }]
]);


function mascaraCpf(value, evente)
{
  var data = value.value;
  var chare = mascaraNoChar(evente);
  var key = typeof window.event != "undefined" ? window.event.keyCode : evente.which;

  if((key == 0) || (key == 8))
    return true;

  if(chare) {
      if (data.length == 3 || data.length == 7) {
        data = data + ".";
        value.value = data;
        return true;
      }else if (data.length == 11) {
        data = data + "-";
        value.value = data;
        return true;
      }
  } else {
      return false;
  }
}


function mascaraCnpj(value){
  var data = value.value;
  if (data.length == 2){
    data = data + ".";
    value.value = data;
    return true;
  }
  if (data.length == 6){
    data = data + ".";
    value.value = data;
    return true;
  }
  if (data.length == 10){
    data = data + "/";
    value.value = data;
    return true;
  }
  if (data.length == 15){
    data = data + "-";
    value.value = data;
    return true;
  }
}


var __QTY_VAL = {};

function incrementProductValue(qty) {
    
    handleProductValue(qty, 'add');
}
function decrementProductValue(qty) {
    handleProductValue(qty, 'sub');
}

function handleProductValue(qty, operator) {
    field = document.getElementById('qty_' + qty);
    if (isNaN(field.value)) {
        field.value = 0;
    } else {
        if (operator == 'add') {
            field.value = Number(field.value) + 1;
        } else {
            if (parseInt(field.value) > 0) {
                field.value = Number(field.value) - 1;
            }
        }
    }
}

function clearProductValue(obj)
{
    __QTY_VAL[obj.id] = obj.value;
    obj.value = '';
}

function repopulateProductValue(obj)
{
    if (obj.value.trim() == '') {
        obj.value = __QTY_VAL[obj.id];
    }
}
function getCustomerAddressByCep(data, url)
{
	if (data.postcode)
	{
		onepage = false;
		postcode = data.postcode; 
	}
	else
	{
		onepage = true;
		postcode = data['shipping:postcode'];
	}
	
	if ((postcode.value.length == 8 || postcode.value.length == 9) && postcode.value != customerAddress.cep)
	{
		customerAddress.customCep = true;
		customerAddress.cep = postcode.value;
		ajaxUrl = url + '?cep=' + postcode.value;
		_getCustomerAddress(ajaxUrl, 'zip-loader', 1, onepage);
	}
	else if (postcode.value.length == 0)
	{
		customerAddress.customCep = false;
	}
}

function getCepByCustomerAddress(data, url)
{
	if (data.street_1)
	{
		onepage = false;
		street = data.street_1;
		bairro = data.bairro;
	}
	else
	{
		onepage = true;
		street = data['shipping:street1'];
		bairro = data['shipping:bairro'];
	}

	if (customerAddress.customCep == false && street.value.length > 0 && street.value != customerAddress.rua && _isNewStreetAddress(street.value))
	{
		customerAddress.rua = street.value;
		ajaxUrl = url + '?rua=' + street.value + '&bairro=' + bairro.value;
		_getCustomerAddress(ajaxUrl, 'street_1-loader', 2, onepage);
	}
	
}


function _getCustomerAddress(url, loader, type, onepage)
{
	jQuery('#' + loader).show();

	new Ajax.Request(url, 
	{
		method: 'GET',
		onSuccess: function (transport) 
		{
			if (transport.responseJSON.success)
			{
				retornoEnderecosAjax = transport.responseJSON.data;

				if (transport.responseJSON.data.length == 1)
				{
					selectCustomerAddress(0, onepage);
				}
				else
				{
					jQuery('#dialog_cep_endereco').dialog({
						width: 600,
						height: 280,
						modal: true,
						resizable: false,
						title: 'Complemento de endereço'
					});
					
					lista = '';
					
					for (i=0; i<transport.responseJSON.data.length; i++)
					{
						lista = lista + '<li><a href="javascript:selectCustomerAddress(' + i + ', ' + onepage + ');">' + transport.responseJSON.data[i].bairro + ', ' + transport.responseJSON.data[i].rua + '</a></li>';
					}
					
					jQuery('#cep_enderecos_lista').html(lista);
				}
				
				jQuery('#' + loader).hide();
			}
			else
			{
				alert('Desculpe, não atendemos o CEP informado.');
				jQuery('#' + loader).hide();
			}
		},
		onFailure: function (transport) 
		{
			//jQuery('#dialog_cep').dialog('close');
			alert('Erro ao realizar consulta do CEP. Por favor, tente novamente.');
			
			jQuery('#' + loader).hide();
		}
	});
}

function _isNewStreetAddress(street)
{
	return (street.substr(0, customerAddress.rua.length) != customerAddress.rua || customerAddress.rua == '');
}

function selectCustomerAddress(idx, onepage)
{
	zip = 'zip';
	bairro = 'bairro';
	street = 'street_1';
	
	if (onepage)
	{
		zip = 'shipping:postcode';
		bairro = 'shipping:bairro';
		street = 'shipping:street1';
	}
	
	$(zip).value = formataCep(retornoEnderecosAjax[idx].cep);
	$(bairro).value = retornoEnderecosAjax[idx].bairro_id;
	$(street).value = retornoEnderecosAjax[idx].rua;
	
	jQuery('#dialog_cep_endereco').dialog('close');
}

function formataCep(value)
{
	return value.substr(0, 5) + '-' + value.substr(5, 3);
}



function checkForEnter(event) 
{
	if (event.keyCode == 13) 
	{
		textboxes = jQuery("form.enterAsTab input:visible, select:visible, textarea:visible, button:visible");
		
		currentBoxNumber = textboxes.index(this);
        
		if (textboxes[currentBoxNumber + 1] != null) 
		{
			nextBox = textboxes[currentBoxNumber + 1];
			nextBox.focus();
			nextBox.select();
			event.preventDefault();
            return false;
        }
    }
}

jQuery(document).ready(function() {

    textboxes = jQuery("form.enterAsTab input, select");

    if (jQuery.browser.mozilla) 
    {
    	jQuery(textboxes).keypress(checkForEnter);
    } 
    else 
    {
    	jQuery(textboxes).keydown(checkForEnter);
    }
});
