function getRandomDaily(){
  var todayDaily = getTodayDaily();
  if( todayDaily == false ) { 
    //allDailies solo los no activos
    var allDailies = getNotActiveDailies();
    var randNumber = Math.floor((Math.random()*allDailies.length)); 
    var todayDaily = allDailies[ randNumber ];
    var allDailiesDB = JSON.parse(localStorage.allDailies); 
    
    modifyAllDailiesById(todayDaily.id, 'status', 0);
     
    var activeDaily = new Object();
    activeDaily['id'] = todayDaily.id;
    activeDaily['dateTimeCreated'] = moment().format('YYYY-MM-DD HH:mm:ss');
    activeDaily['dateCreated'] = moment().format('YYYY-MM-DD');
    activeDaily['status'] = 0;
    activeDaily['datePass'] = null;
    activeDaily['errors'] = 0;

    var arrActiveDailies = JSON.parse(localStorage.activeDailies);
    arrActiveDailies.push( activeDaily );
    var jsonActiveDaily = JSON.stringify( arrActiveDailies );
  
    localStorage.activeDailies = jsonActiveDaily;
    
    return allDailies[ randNumber ];
  }else{
    return  getDailyById( todayDaily.id );
  }
  
}

function getNotActiveDailies(){
  var allDailies = JSON.parse(localStorage.allDailies);
  var activeDailies = JSON.parse(localStorage.activeDailies);
  var notActiveDailies = new Array();
  var found = false;
  
  for (var i=0; i<allDailies.length; i++){
    
    for (var j=0; j<activeDailies.length; j++){
      if( allDailies[i].id == activeDailies[j].id ){
        found = true;
      }
    }
    if(!found)notActiveDailies.push(allDailies[i]);
    found = false;
  }
  return notActiveDailies;
}

function getTodayDaily(){
  var activeDailies = JSON.parse( localStorage.activeDailies );
  var currentDate = moment().format('YYYY-MM-DD');
  for (var i=0; i<activeDailies.length; i++){
    if( activeDailies[i].dateCreated == currentDate ) return activeDailies[i];
  }
  return false;
}

function getDailyById( id ){
  var allDailies = JSON.parse(localStorage.allDailies);
  for (var i=0; i<allDailies.length; i++){
    if( allDailies[i].id == id ) return allDailies[i];
  }
  return false;
}

function getActiveDailyById( id ){
  var activeDailies = JSON.parse( localStorage.activeDailies );
  for (var i=0; i<activeDailies.length; i++){
    if( activeDailies[i].id == id ) return activeDailies[i];
  }
  return false;
}

function getPassedDailies(){
    var activeDailies = JSON.parse( localStorage.activeDailies );
    var passedDailies = new Array();
    for (var i = 0; i < activeDailies.length; i++ ){
      if (activeDailies[i].status == 1){
        passedDailies.push(getDailyById( activeDailies[i].id ) );
      }
    }
    return passedDailies;
}

function getActivesDailiesByPassed(){
    var activeDailies = JSON.parse( localStorage.activeDailies );
    var notPassedDailies = new Array();
    var passedDailies = new Array();
    for (var i = 0; i < activeDailies.length; i++ ){
      if (activeDailies[i].status == 1){
        passedDailies.push(getDailyById( activeDailies[i].id ) );
      }
      else if (activeDailies[i].status == 0){
        notPassedDailies.push(getDailyById( activeDailies[i].id ) );
      }
    }
    var respActivesDailies = new Object();
    respActivesDailies['notPassed'] = notPassedDailies;
    respActivesDailies['passed'] = passedDailies;
    
    return respActivesDailies;
}

function getDailiesToReview(){
  var dailies = getActivesDailiesByPassed();
  var dailiesNotPassed = dailies.notPassed;
  var dailiesWithErrors = new Array();
  for (var i = 0; i < dailiesNotPassed.length; i++ ){

    var activeDaily = getActiveDailyById( dailiesNotPassed[i].id );
    
    var dateCreated = activeDaily.dateCreated;
    var year = dateCreated.substring(0, 4);
    var month = dateCreated.substring(5, 7);
    var day = dateCreated.substring(8, 10);
    if( !isToday(year, month, day) ) dailiesWithErrors.push( dailiesNotPassed[i] );
  }

  return dailiesWithErrors;
}

function isToday(year, month, day){
  var dateToday = new Date();
  if ( parseInt(day, 10) == parseInt(dateToday.getDate(), 10) && parseInt(month, 10)-1 == parseInt(dateToday.getMonth(), 10) && parseInt(year) == parseInt(dateToday.getFullYear()) ){
    return true; 
  }
  else{
    return false;
  }
}

function howMany(){
  var allDailies = JSON.parse(localStorage.allDailies);
  var activeDailies = JSON.parse( localStorage.activeDailies )
  var howMany = allDailies.length - activeDailies.length;
  return howMany;
}


function getSupportDailies(){
  var allDailies = JSON.parse(localStorage.allDailies);
  var activeDailies = JSON.parse( localStorage.activeDailies );
  var arrSupport = new Array();
  for(var i=0; i<activeDailies.length;i++){
    arrSupport.push( getDailyById( activeDailies[i].id ) );
  }
  
  return arrSupport;
}

function modifyAllDailiesById(id, field, value){
  var allDailiesAux = JSON.parse(localStorage.allDailies);
  
  var found = false;
  for(var i=0; i<allDailiesAux.length;i++){
    if(allDailiesAux[i].id == id) {

      allDailiesAux[i][field] = value;

      
      localStorage.allDailies = JSON.stringify( allDailiesAux ) ; 
      
      found = true;
    }

  }

  return found;
}

function getPoints(){
   var oldPoints = JSON.parse( localStorage.points );
   var allDailies = JSON.parse( localStorage.allDailies );
   var passedDailies = getPassedDailies();
    
   var points = new Object();
   points['passed'] = passedDailies.length;
   points['all'] = allDailies.length;

   
   if( points['passed'] == oldPoints['passed'] ){
    points['new'] = false; //false
   }else{
    points['new'] = true;
   }

   localStorage.points =  JSON.stringify(points) ;

   return points;
}


function upDateData(){
  setLoader('#wrapper');
  if( navigator.onLine ) {
    $.ajax({
          url : 'http://dailes.w.pw/update_actives',
          data : { tokenUser : localStorage.userToken, dailyActives : localStorage.activeDailies },
          type : 'POST',
          dataType : 'json',
          error : function(jqXHR, status, error) {
              console.log('Disculpe, existió un problema');
          },
          complete : function(jqXHR, status) {
              cleanLogOut();
              console.log('Petición realizada');
          }
    });
  }else{
    alert('You don\'t have internet conexion. Your data wasn\'t updated');
    cleanLogOut();
  }

}

function removeById( id, array ){
  var respArr = new Array();
  for(var i = 0; i < array.length; i++ ){
    if(array[i].id != id ) respArr.push(array[i]);
  }
  return respArr;
}

function cleanLogOut(){
  localStorage.userLogin = 0;
  localStorage.userToken = '';
  localStorage.allDailies =JSON.stringify( new Array() );
  localStorage.activeDailies = JSON.stringify( new Array() );
  localStorage.points = JSON.stringify( new Object() );
  localStorage.dailyAlarm = '';
  localStorage.btnAnswerStatus = 0;
  localStorage.btnDailyStatus = 0;
  localStorage.counterReviewAlarm = 0;

  removeAlarmAll();
  setTimeout(function(){
    stopLoader();
    window.close();
    window.location.href = '#/login';
  }, 1000);
}