function updatePosition() {
  var c_wh = {
    w: $('.modalContainer').width(),
    h: $('.modalContainer').height()
  };
  var b_wh = {
    w: $(window).width(),
    h: $(window).height()
  };
  var isCenter = b_wh.h > c_wh.h + 30;
  $('.modalContainer').css({
    position:'absolute',
    top: (isCenter ? b_wh.h / 2 - c_wh.h / 2 : 30) + 'px',
    left: (b_wh.w / 2 - c_wh.w / 2) + 'px'
  });
  $(window).scrollTop(0);
  if ($.browser.msie && !isCenter) {
    $('body').css({
      height: (c_wh.h + 30) + 'px'
    });
    $('.modalOverlay').css({
      height: $('body').height() + 'px'
    });
  }
}

function album(url) {
  $.blockUI({
    message: '<img alt="Carregando..." src="app/main/templates/img/ajax-loader.gif"/>',
    css: {
      border:'3px solid #D71315',
      padding:'10px'
    },
    overlayCSS:  { 
      backgroundColor:'#000000', 
      opacity:        '0.8' 
    }
  });

  $.get(url, function(data) {
    $.unblockUI();
    $(data).modal({
      close: false,
      overlayCss: {
        backgroundColor:'#000000',
        opacity:'80%',
        height: '100%'
      }
    });
    
    updatePosition();
  });
}

function carregarContato() {
  if ($('#js_con_frm').length) {
    $('#js_con_nome').focus();
    $('#js_con_frm').validate({
      rules: {
        con_nome: 'required',
        con_email: {
          required: true,
          email: true
        },
        con_mensagem: 'required'
      },
      submitHandler: function(form) {
        $(form).ajaxSubmit({
          dataType: 'json',
          success: function(data) {
            if (data) {
              $(form).resetForm();
              alert('Mensagem enviada com sucesso.');
            } else {
              alert('Desculpe, ocorreu um erro ao enviar sua mensagem.');
            }
          }
        });
      }
    });
  }
}

function carregarFichaCadastral() {
  if ($('#js_fic_frm').length) {
    $('#js_fic_nometitular').focus();
    $('#js_fic_frm').validate({
      rules: {
        fic_nometitular: 'required',
        fic_tipoassociado: 'required',
        fic_tipocompetidor: 'required',
        fic_identidade: 'required',
        fic_cpf: 'required',
        fic_datanascimento: 'required',
        fic_endereco: 'required',
        fic_bairro: 'required',
        fic_cidade: 'required',
        fic_estado: 'required',
        fic_cep: 'required',
        fic_telefone: 'required',
        fic_celular: 'required',
        fic_email: {
          required: true,
          email: true
        },
        'fic_dep_datanascimento1': {required: '#js_fic_dep_nome1:filled'},
        'fic_dep_tipo1': {required: '#js_fic_dep_nome1:filled'},
        'fic_dep_datanascimento2': {required: '#js_fic_dep_nome2:filled'},
        'fic_dep_tipo2': {required: '#js_fic_dep_nome2:filled'},
        'fic_dep_datanascimento3': {required: '#js_fic_dep_nome3:filled'},
        'fic_dep_tipo3': {required: '#js_fic_dep_nome3:filled'},
        'fic_dep_datanascimento4': {required: '#js_fic_dep_nome4:filled'},
        'fic_dep_tipo4': {required: '#js_fic_dep_nome4:filled'},
        'fic_dep_datanascimento5': {required: '#js_fic_dep_nome5:filled'},
        'fic_dep_tipo5': {required: '#js_fic_dep_nome5:filled'}
      },
      errorPlacement: function(error, element) {
        element.parent().find('div').html(error);
      },
      submitHandler: function(form) {
        var LOADER_ID;
        $(form).ajaxSubmit({
          dataType: 'json',
          beforeSubmit: function(formData, jqForm, options) {
            $.blockUI({
              message: 'Aguarde...'
            });
            LOADER_ID = setTimeout(function() {
              $.blockUI({
                message: 'Ainda enviando, aguarde por favor...'
              });
              LOADER_ID = setTimeout(function() {
                $.unblockUI();
                alert('O formulário não pôde ser enviado.\nVerifique sua conexão com a Internet e tente novamente.');
              }, 15000);
            }, 15000);
          },
          success: function(data) {
            $.unblockUI();
            if (data) {
              alert('Seu cadastro foi efetuado com sucesso!');
              $(form).resetForm();
              $(window).scrollTop(0);
              $('#js_fic_nometitular').focus();
            } else alert('Desculpe, houve um erro durante o envio do formulário.');
            clearTimeout(LOADER_ID);
          }
        });
      }
    });
    
    $('#js_fic_cpf').mask('999.999.999-99');
    $('#js_fic_datanascimento,#js_fic_datanascimento1,#js_fic_datanascimento2,#js_fic_datanascimento3,#js_fic_datanascimento4,#js_fic_datanascimento5').mask('99/99/9999');
    $('#js_fic_cep').mask('99.999-999');
    $('#js_fic_telefone,#js_fic_celular,#js_fic_fax').mask('(99) 9999-9999');
  }
}

function carregarFichaInscricao() {
  if ($('#js_insc_frm').length == 0) return;
  $('#js_insc_nome').focus();
  $('#js_insc_frm').validate({
    rules: {
      insc_nome: 'required',
      insc_telefone: 'required',
      insc_celular: 'required',
      insc_email: {
        required: true,
        email: true
      },
      insc_animalnome: 'required',
      insc_animalregistro: 'required',
      insc_cavaleiro: 'required',
      insc_cavaleironasc: 'required'
    },
    errorPlacement: function(error, element) {
      if (element.attr('type') == 'checkbox') {
        $('#js_errorstring').html(error.text('Escolha pelo menos uma modalidade.'));
      }
      else {
        element.parent().find('div').html(error);
      }
    },
    submitHandler: function(form) {
      var LOADER_ID;
      $(form).ajaxSubmit({
        dataType: 'json',
        beforeSubmit: function(formData, jqForm, options) {
          $.blockUI({
            message: 'Aguarde...'
          });
          LOADER_ID = setTimeout(function() {
            $.blockUI({
              message: 'Ainda enviando, aguarde por favor...'
            });
            LOADER_ID = setTimeout(function() {
              $.unblockUI();
              alert('O formulário não pôde ser enviado.\nVerifique sua conexão com a Internet e tente novamente.');
            }, 15000);
          }, 15000);
        },
        success: function(data) {
          $.unblockUI();
          if (data) {
            alert('Sua inscrição foi efetuada com sucesso!\nFoi enviado um e-mail para ' + $('#js_insc_email').val() + '. (Verifique sua caixa de SPAM / Lixo Eletrônico)');
            $(form).resetForm();
            $('#js_dadosdupla :text').attr('disabled', true);
            $(window).scrollTop(0);
            $('#js_insc_nome').focus();
          } else alert('Desculpe, houve um erro durante o envio do formulário.');
          clearTimeout(LOADER_ID);
        }
      });
    }
  });
  
  $(':checkbox').rules('add', {
    required: function() {
      return $(':checkbox:checked').length < 1;
    }
  });
  
  $('.js_dupla').change(function() {
    if ($('.js_dupla').is(':checked')) {
      $('#js_dadosdupla :text').attr('disabled', false);
    } else {
      $('#js_dadosdupla :text').attr('disabled', true);
    }
  });
  
  $('#js_insc_cavaleironasc,#js_insc_duplacavaleironasc').mask('99/99/9999');
  $('#js_insc_telefone,#js_insc_celular').mask('(99) 9999-9999');
}

function carregarCadastroEvento() {
  if ($('#js_cadastroevento_frm').length == 0) return;
  $('#js_cadastroevento_nome').focus();
  $('#js_cadastroevento_frm').validate({
    rules: {
      cadastroevento_nome: 'required',
      cadastroevento_datainicio: 'required',
      cadastroevento_datatermino: 'required',
      cadastroevento_cidadeuf: 'required',
      cadastroevento_sobreevento: {
        maxlength:500
      }
    },
    messages: {
      cadastroevento_sobreevento: jQuery.format("A mensagem não pode conter mais de {0} caracteres.")
    },
    submitHandler: function (form) {
      $(form).ajaxSubmit({
        dataType: 'json',
        beforeSubmit: function() {
          $.blockUI({message: 'Por favor, aguarde...'});
        },
        error: function(xhr, statusText, errorThrown) {
          $.unblockUI();
          alert('Desculpe, ocorreu um erro. Tente novamente.');
        },
        success: function(data) {
          $.unblockUI();
          if (data) {
            $(form).resetForm();
            alert('Suas informações foram enviadas com sucesso.');
          }
        }
      });
    }
  });
  $('#js_cadastroevento_datainicio, #js_cadastroevento_datatermino').mask('99/99/9999');
}

function validateCPF(cpf) {
  cpf = cpf.replace(/[\.-]/g, '');
  var num = cpf.substr(0, 9);
  if (num == '000000000' || num == '111111111' || num == '222222222' || 
      num == '333333333' || num == '444444444' || num == '555555555' ||
      num == '666666666' || num == '777777777' || num == '888888888' ||
      num == '999999999') return false;

  var digits = cpf.substr(9, 2);
  var d1 = 0;
  var d2 = 0;
  for (var i = 0; i < 9; i++) d1 += Number(num.charAt(i)) * (10 - i);
  d1 = 11 - d1 % 11;
  if (d1 > 9) d1 = 0;
  num += d1;
  
  for (var i = 0; i < 10; i++) d2 += Number(num.charAt(i)) * (11 - i);
  d2 = 11 - d2 % 11;
  if (d2 > 9) d2 = 0;
  return digits == (String(d1) + String(d2));
}

function carregarEnquete() {
  if ($('#frmEnquete').length == 0) return;
  
  $('#nome').focus();
  $('#cpf').mask('999.999.999-99', {
    completed: function() {
      if (!validateCPF(this.val())) {
        alert('CPF inválido!');
        this.val('');
        this.focus();
      }
    }
  });
  $('#telefone1,#telefone2').mask('(99)9999-9999');
  
  $('#frmEnquete').submit(function() {
    if ($('#nome').val() == '') {
      alert('Informe seu nome.');
      return false;
    } else if ($('#cpf').val() == '' || $('#cpf').val() == '___.___.___-__') {
      alert('Informe seu CPF.');
      return false;
    }
    var p = 0, len = $('.p').length;
    $('.p').each(function() {
      if ($(this).val() != '') p++;
    });
    if (p < len - 1) {
      alert('Todas as perguntas devem ser respondidas.');
      return false;
    }
  });
}

function modalNoticia(id) {
  $.blockUI({
    message: '<div style="height:400px"><img alt="Carregando..." style="position:relative;top:192px" src="app/main/templates/img/ajax-loader.gif"/></div>',
    css: {
      border:'3px solid #D71315',
      padding:'10px',
      top: (($(window).height() - 400) / 2) + 'px',
      left: (($(window).width() - 600) / 2) + 'px',
      width:'600px'
    },
    overlayCSS:  { 
      backgroundColor:'#000000', 
      opacity:        '0.8' 
    },
    centerX: false,
    centerY: false
  });
  
  $.get('?route=Home/modalNoticia/' + id, function(data) {
    $('.blockUI').css({
      cursor: 'default'
    });
    $('.blockMsg').html(data);
    $('.noticia_fechar').click($.unblockUI);
  });
  return false;
}

function flyer() {
  if (!$('#flyer').length) $('body').append('<div id="flyer" class="modal" title="Clique para fechar"></div>');
  $('#flyer').html('<img src="app/main/templates/eventos/flyer.jpg" width="800" height="566" alt=""/>');
  $('#flyer').css({
    backgroundColor:'#fff',
    left:'50%',
    top:($(window).height() / 2 - $('#flyer').height() / 2 + $(window).scrollTop()) + 'px',
    marginLeft:'-400px',
    position:'absolute',
    zIndex:10
  });
  $('#flyer').click(function() {
    $('#flyer').remove();
  });
}

$(function() {
  $('a[@rel=foto]').click(function() {
    album($(this).attr('href'));
    return false;
  });
  
  $('a[href=flyer]').click(function() {
    flyer();
    return false;
  });
  
  $('.publi_cycle').cycle({
    timeout:10000
  });
  
  $.validator.messages.required = 'Preenchimento obrigatório.';
  $.validator.messages.email = 'E-mail inválido.';
  carregarContato();
  carregarFichaCadastral();
  carregarFichaInscricao();
  carregarCadastroEvento();
  carregarEnquete();
});