// Dom7
var $ = Dom7;

// Theme
var theme = 'auto';
if (document.location.search.indexOf('theme=') >= 0) {
  theme = document.location.search.split('theme=')[1].split('&')[0];
}

// Init App
var app = new Framework7({
  pushState: true,
  pushStateSeparator: '#page/',
  pushStateRoot: '/m/',
  id: 'com.sysfbet.fbet',
  root: '#app',
  theme: theme,
  smartSelect: {
    openIn: 'page',
    closeOnSelect: true,
    url: 'select/'
  },
  data: function () {
    return {
      user: {
        firstName: 'John',
        lastName: 'Doe',
      },
    };
  },
  methods: {
    helloWorld: function () {
      app.dialog.alert('Hello World!');
    },
  },
  dialog: {
    preloaderTitle: 'Um instante...',
    buttonCancel: 'Cancelar',
  },
  touch: {
    disableContextMenu: false,
  },
  routes: routes,
  vi: {
    placementId: 'pltd4o7ibb9rc653x14',
  },
});
var $$ = Dom7;
var mainView = app.views.create('.view-main', { pushState: true, pushStateSeparator: '#page/', pushStateRoot: '/m/' });

//var devId = Website2APK.getUniqueDeviceID();
//Website2APK.showToast("Bem-vindo ao FScores!");

function requestAjax(myurl, cb){
   var xmlhttp;
   if (window.XMLHttpRequest){
       xmlhttp=new XMLHttpRequest();}
   else{
       xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}

    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            if( typeof cb === 'function' )
                cb(xmlhttp.responseText);
        }
    }

   xmlhttp.open("GET",myurl,true);
   xmlhttp.send();

}

function login(redirect){
  showLoaderText('Validando...');
  var user = document.getElementById('loginFormUser').value;
  var pass = document.getElementById('loginFormPass').value;
  var salvar = '';
  if(document.getElementById('loginFormSaveSession').checked){ salvar = 'on'; }

  requestAjax('/api/login?user='+user+'&pass='+pass+'&salvar='+salvar, function(d){
    app.preloader.hide();
    app.dialog.close();
    var ret = JSON.parse(d);
    if(ret.status == 'success'){
      showLoaderText('Redirecionando...');
      app.router.navigate(redirect, { reloadCurrent: true, clearPreviousHistory: true, ignoreCache: true });
    } else {
      app.dialog.alert(ret.error, 'Erro!');
    }
  });
}

function sair(){
  showLoaderText('Saindo...');
  requestAjax('/sair', function(d){
    app.preloader.hide();
    app.dialog.close();
    app.router.navigate('/', { reloadCurrent: true, clearPreviousHistory: true, ignoreCache: true });
  });
}

function filterCashierCoupons(type){
  showLoaderText('Carregando...');
  var date = document.getElementById('cashierDate').value;
  var enddate = document.getElementById('cashierEnddate').value;
  app.router.navigate('/'+type+'/?type=personal&date='+date+'&enddate='+enddate, { reloadCurrent: true });
}

function cancelCoupon(code){
  app.dialog.confirm('Deseja mesmo cancelar o bilhete #'+code+'?', 'Confirmação', function(){
    showLoaderText('Cancelando...');
    requestAjax('../m/scripts/cancelCoupon.php?registro='+code, function(d){
      app.dialog.close();
      app.preloader.hide();
      if(d == '1'){
        document.getElementById('badgeCoupon'+code).innerHTML = 'Cancelado';
        document.getElementById('badgeCoupon'+code).className = 'badge color-black';
        app.dialog.alert('O bilhete foi cancelado.', 'Pronto!');
      }
      else { app.dialog.alert(d, 'Erro!'); }
    });
  });
}

function filterMatches(){
  showLoaderText('Carregando...');
  var data = document.getElementById('dataFilterMatch').value;
  var sport = document.getElementById('sportFilterMatch').value;
  document.getElementById('matchesListByFilter').innerHTML = '';
  requestAjax('/m/scripts/getMatchesFilter.php?data='+data+'&esporte='+sport, function(d){
    var ret = JSON.parse(d);
    var total_qtd = 0;
    Object.keys(ret).forEach(function(k){
        var i = k.replace(' ', '-');
        i = i.replace('á', 'a');
        i = i.replace('ã', 'a');
        i = i.replace('â', 'a');
        i = i.replace('é', 'e');
        i = i.replace('ê', 'e');
        i = i.replace('í', 'i');
        i = i.replace('ç', 'c');
        i = i.replace('ó', 'o');
        i = i.replace('ô', 'o');
        i = i.replace('õ', 'o');
        i = i.replace('ú', 'u');
        var qtd = 0;
        for(var b in ret[k]){ for(var c in ret[k][b]){ qtd = parseInt(qtd) + parseInt(1); total_qtd = parseInt(total_qtd) + parseInt(1); } }
        if(qtd > 0){
          document.getElementById('matchesListByFilter').innerHTML += '<li> <a href="/partidas/?esporte='+sport+'&pais='+k+'&data='+data+'" class="item-link item-content"> <div class="item-media"><span class="flags flags-category flags-sports flags--md flags--'+i+'"></span></div> <div class="item-inner"> <div class="item-title">'+k+'</div> <div class="item-after"><div class="chip color-orange mini-chip"> <div class="chip-label">'+qtd+'</div> </div></div> </div> </a> </li>';
        }
    });
    if(total_qtd == 0){ document.getElementById('matchesListByFilter').innerHTML = '<li style="text-align: center;"><h4>Não há jogos disponíveis para esta data.</h4></li>'; }
    app.dialog.close();
  });

}

function confirmDelete(cod, goIndex){
  app.dialog.confirm('Você tem certeza que deseja remover o bilhete '+cod+'?', 'Tem certeza?', function(){
    app.dialog.preloader('Apagando...');

    app.request.get('pages/bilhetes/apagar.php?sleep=1&codigo='+cod, function(data) {
      app.dialog.close();

      if(data == '1'){
        document.getElementById('bilhete'+cod).style.display = 'none';

        if(goIndex == true){ location.href = '/'; }
      }
      else {
        app.dialog.alert(data, 'Erro');
      }
    });
  });
}

function showLoader(){
  app.preloader.show();
  setTimeout(function(){ app.preloader.hide(); }, 5000);
  return false;
}

function showLoaderText(t){
  var sec = 5000;
  if(t == ''){ t = 'Carregando...'; }
  if(t == 'Finalizando...'){ sec = 12000; }
  app.dialog.preloader(t);
  setTimeout(function(){ app.dialog.close(); }, sec);
  return false;
}

function getCouponInfo(callback){
  var json = '';
  $.get('scripts/getCouponInfo.php', function(d){
    JSON.parse(d);
    json = d;
    console.log('getCouponInfo returns: '+json);
    callback(json);
  });
}

function promptConferirBilhete(){
  app.dialog.prompt('Digite o código do bilhete:', 'Conferir Bilhete', function(v){
    if(v == ''){ app.dialog.alert('Informe um código válido.', 'OOOOPS!'); return false; }
    showLoaderText('Processando...');
    app.router.navigate('/visualizar-bilhete/?code='+v);
  });
}

function promptProcessarPIN(){
  app.dialog.prompt('Digite o código do PIN:', 'Processar PIN', function(v){
    if(v == ''){ app.dialog.alert('Informe um código válido.', 'OOOOPS!'); return false; }
    showLoaderText('Processando...');
    app.router.navigate('/processar-pin/?code='+v);
  });
}

var liveSignals;
var liveMoreOdds;

$$(document).on('page:init', function (e, page) {
    app.dialog.close();
    app.preloader.hide();

    var calendar = app.calendar.create({
        inputEl: '.calendario',
        openIn: 'customModal',
        headerPlaceholder: 'Selecione a data',
        header: true,
        footer: true,
        toolbarCloseText: 'Fechar',
        dateFormat: 'yyyy-mm-dd',
        monthNames: ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto' , 'Setembro' , 'Outubro', 'Novembro', 'Dezembro'],
        dayNamesShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'],
        closeOnSelect: true
    });

    var calendar2 = app.calendar.create({
        inputEl: '.calendario2',
        openIn: 'customModal',
        headerPlaceholder: 'Selecione a data',
        header: true,
        footer: true,
        toolbarCloseText: 'Fechar',
        dateFormat: 'yyyy-mm-dd',
        monthNames: ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto' , 'Setembro' , 'Outubro', 'Novembro', 'Dezembro'],
        dayNamesShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'],
        closeOnSelect: true
    });

    // Page Data contains all required information about loaded and initialized page
    var pagename = page.route.name;
    var url = page.route.url;
    var url_atual = window.location.href;
    var getvars = page.route.query;
    var pagenamePrev = page.router.previousRoute.name;

    if(pagename == 'nova-aposta'){ filterMatches(); }

    // Atualiza informações
    console.log('--------------------------------------- Pagename: '+pagename+' ---------------------------------------');

    // Para o caso de AOVIVO MAIS OPCOES
    if(pagename == 'mais-opcoes-aovivo'){
      openMoreOdds(getvars["match"], getvars["match_name"]);
      liveMoreOdds = setInterval(function(){ openMoreOdds(getvars["match"], getvars["match_name"]); }, 5000);
      clearInterval(liveSignals);
    } else {
      console.log('Stopping more odds.');
      clearInterval(liveMoreOdds);
    }

    getCouponInfo(function(d){
        if(d == undefined){ console.log('ERRO CALCRETURN!'); return false; }
        var d = JSON.parse(d);
        odds = d.odds;
        var divs = document.getElementsByClassName( 'couponqtd' );

        [].slice.call( divs ).forEach(function ( div ) {
            div.innerHTML = d.qtd;
        });
    });

    // Preenche informações dos valores
    var priceReturn = app.form.getFormData('#priceReturnBetForm');
    app.form.fillFromData('#priceReturnBetFormFinish', priceReturn);

    var divs = document.getElementsByClassName( 'priceReturnBetForm' );

    [].slice.call( divs ).forEach(function ( div ) {
      app.form.fillFromData(div, priceReturn);
    });

    console.log('PRICERETURN PREENCHIDO! => '+JSON.stringify(priceReturn));


    // Para o caso de AOVIVO
    if(pagename == 'aovivo' || pagenamePrev == 'mais-opcoes-aovivo'){
      getLiveSignal();
      liveSignals = setInterval(function(){ getLiveSignal(); }, 5000);
      clearInterval(liveMoreOdds);
    } else {
      clearInterval(liveSignals);
    }

});