LightboxOptions.fileLoadingImage = 'css/wait.gif'
LightboxOptions.fileBottomNavCloseImage = 'css/close.gif'
LightboxOptions.labelImage = 'Figura';
LightboxOptions.labelOf = '/';

Validation.methods["_LikeNoIDIEverSaw_"].error = "Validação falhou.";
Validation.methods["IsEmpty"].error = "Validação falhou.";
Validation.methods["required"].error = "Este campo é obrigatório.";
Validation.methods["validate-number"].error =
  "Favor digitar um número válido.";
Validation.methods["validate-digits"].error =
  "Favor utilizar apenas números. Evite espaços ou outros caracteres como pontos e vírgulas.";
Validation.methods["validate-alpha"].error =
  "Favor utilizar apenas letras (a-z).";
Validation.methods["validate-alphanum"].error =
  "Favor utilizar apenas letras (a-z) e números. Nenhum espaço ou outro caracteresão permitidos.";
Validation.methods["validate-date"].error =
  "Favor digitar uma data válida.";
Validation.methods["validate-email"].error =
  "Favor digitar um endereço de e-mail válido.";
Validation.methods["validate-url"].error = "Favor digitar uma URL válida.";
Validation.methods["validate-date-au"].error =
  "Favor digitar uma data válida";
Validation.methods["validate-currency-dollar"].error =
  "Favor digitar uma quantia monetária válida. Por exemplo $100.00 .";
Validation.methods["validate-selection"].error = "Favor selecionar algum item";
Validation.methods["validate-one-required"].error =
  "Favor selecionar uma das opções.";

function validateCPF(cpf) {
  var mult = "98765432";
  if(cpf.length!= 11)
    return false;
  for ( var i=0 ; i<10 ; i++ )
  {
    var temp = "";
    for ( var j=0 ; j<11 ; j++ ) temp += String(i);
    if ( temp == cpf ) return false;
  }
  var soma = 10 * parseInt(cpf.substr(0, 1));
  for(var x = 1; x <= 8; x++)
    {
    soma += parseInt(cpf.substr(x, 1)) * parseInt(mult.substr(x - 1, 1));
  }
  var resto = soma % 11;
  var D1 = 0;
  if(!(resto == 0 || resto == 1))
      D1 = 11 - resto;
  if(D1 != parseInt(cpf.substr(9, 1)))
    return false;
  soma = 11 * parseInt(cpf.substr(0, 1)) + 10 * parseInt(cpf.substr(1, 1));
  for(x = 2; x<=8; x++)
  {
    soma += parseInt(cpf.substr(x, 1)) * parseInt(mult.substr(x - 2, 1));
  }
  soma += (2 * parseInt(D1));
  resto = soma % 11;
  var D2 = 0;
  if(!(resto == 0 || resto == 1))
    D2 = 11 - resto;
  if(D2 != parseInt(cpf.substr(10, 1)))
    return false;
  else
    return true;
}

function validateCNPJ(cnpj) {
  var mult1 = "543298765432";
  var mult2 = "654329876543";
  if(cnpj.length != 14)
    return false;
  var soma = 0;
  for(var x = 0; x <= 11; x++)
    soma += parseInt(cnpj.substr(x, 1)) * parseInt(mult1.substr( x, 1));
  var resto = soma % 11;
  var D1=0;
  if(!(resto == 0 || resto == 1))
    D1 = 11 - resto;
  if(D1 != cnpj.substr(12, 1))
    return false;
  soma = 0;
  for(x = 0; x <= 11; x++)
    soma += parseInt(cnpj.substr(x, 1)) * parseInt(mult2.substr(x, 1));
  soma += 2 * parseInt(D1);
  resto = soma % 11;
  var D2=0;
  if(!(resto == 0 || resto == 1))
        D2 = 11 - resto;
  if(D2 != parseInt(cnpj.substr(13, 1)))
    return false;
  else
    return true;
}

function numericPartLength(v)
{
  var j = 0;
  var pattern = /^[0-9]$/;
  for (var i = 0; i < v.length; i++)
    if (pattern.test(v.substr(i, 1)))
      j += 1;
  return j;
}


Validation.add('validate-positive', 'Favor digitar um número positivo.',
  function(v) {
    return Validation.get('IsEmpty').test(v) || (v > 0);
  }
);

Validation.add('validate-address', 'Favor digitar o endereço completo.',
  function(v) {
    var pattern = /^[A-Za-zàáâãèéêìíîòóôõüùúûñç]+ [A-Za-z0-9àáâãèéêìíîòóôõüùúûñçº ]+[, ]+[0-9]+.*$/;
    return Validation.get('IsEmpty').test(v) || pattern.test(v);
  }
);

Validation.add('validate-cpf', 'Favor digitar um CPF válido.', function(v) {
  return Validation.get('IsEmpty').test(v) || validateCPF(v);
});

Validation.add('validate-cnpj', 'Favor digitar um CNPJ válido', function(v) {
  return Validation.get('IsEmpty').test(v) || validateCNPJ(v);
});

Validation.add('validate-cpf-cnpj', 'Favor digitar um CPF ou CNPJ válido.',
  function(v) {
  return Validation.get('IsEmpty').test(v) || validateCPF(v) || validateCNPJ(v);
});


Validation.add('validate-cep', 'Favor digitar um CEP válido.',
  function(v) {
    return Validation.get('IsEmpty').test(v) || numericPartLength(v) == 8;
});

Validation.add('validate-telefone', 'Favor digitar um telefone válido.',
  function(v) {
    return Validation.get('IsEmpty').test(v) || numericPartLength(v) == 8;
});

Validation.add('validate-ddd-telefone', 'Favor digitar um telefone válido com DDD.',
  function(v) {
    return Validation.get('IsEmpty').test(v) || numericPartLength(v) == 10;
});


function applyMask(mask, element) {
  element.maxLength = mask.length;
  element.size = mask.length;
  Event.observe(element, 'keypress', function(event) {
    var key = window.event ? window.event.keyCode : event ? event.which : 0;
    if (key >= 32 && key < 127)
    {
      var ch      = String.fromCharCode(key);
      var pos     = element.value.length;
      while (pos < mask.length)
      {
        var kind = mask.charAt(pos);
        if (kind == '0' && /[0-9]/.test(ch)) {
          element.value += ch; break; }
        else if (kind == 'a' && /[A-Za-z]/.test(ch)) {
          element.value += ch; break; }
        else if (kind == '?' && /[A-Za-z0-9]/.test(ch)) {
          element.value += ch; break; }
        else if (/[0a\?]/.test(kind))
          break;
        else
          element.value += kind;
        pos += 1;
      }
      Event.stop(event);
    }
  });
}



Event.observe(window, 'load', function() {
  $$('a[href!=""]').each(function(a) {
    if (a.readAttribute('href').startsWith('http://')) {
      a.writeAttribute('rel', 'external');
      a.writeAttribute('target', '_blank');
    };
  });

  $$('a[rel=external]').each(function(a) {
    if (a.readAttribute("href"))
      a.writeAttribute('target', '_blank');
  });
  $$('a.msn').each(function(a) {
    Event.observe(a, 'click', function(ev) {
      // oi
      window.open(a.readAttribute('href'), 'msn', "status=0,toolbar=0,location=0,menubar=0,resizeable=1,height=400,width=600");
      Event.stop(ev);
    });
  });

  $$('.flash').each(function(e) {
    Event.observe(e, 'click', function(ev) {
      Effect.BlindUp(e);
    });
    new PeriodicalExecuter(function(pe) {
      Effect.BlindUp(e);
      pe.stop();
    }, 5);
  });

  var firstForm = true;
  $$('#content form').each(function(f) {
    if (f.name != 'pedido')
      new Validation(f, {immediate:true, stopOnFirst: true});
    if (firstForm)
      f.focusFirstElement();
    firstForm = false;
  });

  $$('#download_produto').each(function(e) {
    Event.observe(e, 'change', function(event) {
      var produto = $F('download_produto');
      $('download_alunos').removeClassName('hidden');
      if (produto == 'idescol') {
        $('download_alunos_label').innerHTML = 'Número de alunos';
        $('download_alunos_item').style.display = 'block';
      } else if (produto == 'ideimob') {
        $('download_alunos_label').innerHTML = 'Número de imóveis';
        $('download_alunos_item').style.display = 'block';
      } else if (produto == 'idecond') {
        $('download_alunos_label').innerHTML = 'Número de condomínios';
        $('download_alunos_item').style.display = 'block';
      } else {
        $('download_alunos_item').style.display = 'none';
      }
    });
  });

  $$('#download_cidade, #pedido_cidade, #revenda_cidade').each(function(e) {
    new Ajax.Autocompleter(e, 'autocomplete', 'ajax-cidades.php',
      {paramName: 'busca', minChars: 3, callback: function(name, querystring) {
        var uf_id = e.form.name+'_estado';
        if ($(uf_id)) querystring += '&uf='+$F(uf_id);
        return querystring;
      }
    });
  });

  $$('.validate-ddd-telefone').each(function(e) {
    applyMask('(00) 0000-0000', e);
  });

  $$('.validate-telefone').each(function(e) {
    applyMask('0000-0000', e);
  });

  $$('.validate-cep').each(function(e) {
    applyMask('00000-000', e);
  });

  $$('.validate-cpf-cnpj, .validate-cnpj').each(function(e) {
    applyMask('00000000000000', e);
  });

  $$('.validate-cpf').each(function(e) {
    applyMask('00000000000', e);
  });

  /*$$('.qtde').each(function(e) {
    applyMask('0', e);
  });*/

  $$('input.validate-date, input.validate-date-au').each(function(e) {
    applyMask('00/00/0000', e);
  });

});


