var authToken = '';
var authedUserID = '';

var listOfFavorites = [];
var loginAttempts = 0;

function attemptLogin(attempt){fetch("https://aviation-api.cae.com/v1/users/"+authedUserID,
    {
      "credentials": "include",
      "headers": {
        "accept": "application/json, text/plain, */*",
        "authorization": "Bearer " + authToken,
        "X-Auth": authToken,
        "content-type": "application/json"
      },
      "method": "GET",
      "mode": "cors"
    }).then(function(response) {
      var preloaderImg = $('#profilePreloader').find('img');
      var preloaderLink = $('#profilePreloader').find('a');
      if (response.ok){
        preloaderImg.attr('src', 'https://www.cae.com/assets/images/success.svg')
      }else{
        preloaderImg.attr('src', 'https://www.cae.com/assets/images/fail.png')
        preloaderLink.text('Connection Lost. Please Wait - Attempting to reestablish')
      }
      return response.json();
    })
    .then(function(userInfo) {
      if (userInfo){
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
        setupFavoritingLogic();
        setupAppliedJobs(userInfo);
        loggedInUserFunctionality(userInfo);
        setupProfile(userInfo);
        $(".favoriteJobDetails").show();
      }
    })
    .catch(function(e){
      //console.log(e);
      attemptRefreshToken()
    })
}



function attemptRefreshToken(){
    localStorage.removeItem('userInfo')
    window.location.href = 'https://www.cae.com/?ACT=73&LOGOUT=TRUE&RET_URL=https://aviationjobs.cae.com/'
}



 if (authToken && authedUserID){attemptLogin();}else{localStorage.removeItem('userInfo')}

$(document).ready(function(){
  if (authToken && authedUserID){$('#profilePreloader').show();}else{
    $('.loggedOut').fadeIn();
    loadIncludeDynamically('ajb-includes/auth-links', $('#authLinks'));
    $('.favoriteButton').show()
  }

  
    $('body').on('click','.favoriteButton' , function(e){
      e.preventDefault();
      e.stopPropagation();
    })
  



})

function setupProfile(userInfo){
  loadIncludeDynamically('ajb-includes/auth-links/'+userInfo.firstName, $('#authLinks'), function(){$('#profilePreloader').hide();});
}

/*
  Setup which jobs have been applied to
 */

function setupAppliedJobs(userInfo){
  var appliedJobs = new Array();
  for (var i = 0; i < userInfo.applications.length; i++) {
    $('.job-listing[data-job-id="'+userInfo.applications[i].job.id+'"]').find('.hasApplication').attr('src', 'https://www.cae.com/assets/images/ajb/icons/download-selected.svg')
    appliedJobs.push(userInfo.applications[i].job.slug);
  }

  for (var i = 0; i < appliedJobs.length; i++) {
    if (localStorage.getItem('viewed_jobs')){
      var jobsViewed = JSON.parse(localStorage.getItem('viewed_jobs'));
      if (jobsViewed.indexOf(appliedJobs[i]) == -1){
        jobsViewed.push(appliedJobs[i])
        jobsViewed = JSON.stringify(jobsViewed);
        localStorage.setItem('viewed_jobs', jobsViewed)
      }
    }
    else{
    var jobsViewed = JSON.stringify([appliedJobs[i]]);
      localStorage.setItem('viewed_jobs', jobsViewed)
    }
  }
}

/*
  Logic for successfully authed user
 */

function setupFavoritingLogic(){
  $('.favoriteButton').on("click",function(e){
    e.preventDefault();
    e.stopPropagation();

    $(this).children('img').attr('src', 'https://www.cae.com/assets/ajb-assets/Rolling-1s-20px.gif')
    var idOfJob = $(this).closest('.job-listing').attr('data-job-id');
    //console.log(idOfJob);
    var that = this;
    if (listOfFavorites.indexOf(idOfJob) == -1){
      var action = 'adding';
      listOfFavorites.push(idOfJob)
    }else{
      var action = 'removing';
      listOfFavorites.splice(listOfFavorites.indexOf(idOfJob), 1)
    }
    var favorites = listOfFavorites;
    favorites = favorites.join();
    favorites = JSON.stringify({"favorites" : favorites});
    fetch("https://aviation-api.cae.com/v1/users/"+authedUserID,
    {
      "credentials": "include",
      "headers": {
        "accept": "application/json, text/plain, */*",
        "authorization": "Bearer " + authToken,
        "content-type": "application/json",
        "X-Auth": authToken
      },
      "method": "PUT",
      "mode": "cors",
      "body": favorites
    }).then(function(response) {
      return response.json();
    })
    .then(function(rsp) {
      //console.log(rsp);
      if (action == 'adding'){
        $(that).children('img').attr('src', 'https://www.cae.com/assets/images/ajb/icons/star-selected.svg');
        $(that).closest('.job-listing').attr('data-favorite', '1');
        $(that).next("div").find("p").html("Remove from Favorites")
      }else{
        $(that).children('img').attr('src', 'https://www.cae.com/assets/images/ajb/icons/star.svg');
        $(that).closest('.job-listing').attr('data-favorite', '0');
        $(that).next("div").find("p").html("Add To Favorites")
      }
    });

  })
}

function loggedInUserFunctionality(userInfo){
  //Navigation link for "Hi, Logged in user"
  $('#userName').append(userInfo.firstName);
  $('.loggedIn').fadeIn();
  highlightFavorites(userInfo.favorites);

}
function highlightFavorites(favorites){
  var favoriteJobsViewed = new Array();
  favorites && favorites.length == 0 ? favorites = 'none' : favorites = favorites;
  if (favorites == 'none'){
    
    $('.favoriteButton').not('.hiddenD').show();
    
    return false;
  }
  favorites = favorites ? favorites.split(',') : [];
  listOfFavorites = favorites;
  for (var i = 0; i < favorites.length; i++) {
    // listOfFavorites.push(favorites[i])
    $('.jobDetailsFavoriteButton[data-job-id="'+favorites[i]+'"]').children('img').attr('src', 'https://www.cae.com/assets/images/ajb/icons/star-selected.svg')

    $('.job-listing[data-job-id="'+favorites[i]+'"]').find('.favoriteButton').each(function(){
      $(this).children('img').attr('src', 'https://www.cae.com/assets/images/ajb/icons/star-selected.svg')
    })
    $('.job-listing[data-job-id="'+favorites[i]+'"]').find('.loginTooltip').each(function(){
      $(this).children('p').text('Remove from Favorites');
    })
    $('.job-listing[data-job-id="'+favorites[i]+'"]').attr('data-favorite', '1')

    favoriteJobsViewed.push($('.job-listing[data-job-id="'+favorites[i]+'"]').attr('data-link'))

    $('.favoriteButton[data-job-id="'+favorites[i]+'"]').each(function(){
      $(this).children('img').attr('src', 'https://www.cae.com/assets/images/ajb/icons/star-selected.svg')
    })
  }
  for (var i = 0; i < favoriteJobsViewed.length; i++) {
    if (localStorage.getItem('viewed_jobs')){
      var jobsViewed = JSON.parse(localStorage.getItem('viewed_jobs'));
      if (jobsViewed.indexOf(favoriteJobsViewed[i]) == -1){
        if(favoriteJobsViewed[i] != null){
            jobsViewed.push(favoriteJobsViewed[i])
            jobsViewed = JSON.stringify(jobsViewed);
            localStorage.setItem('viewed_jobs', jobsViewed)
        }
      }
    }
    else{
    var jobsViewed = JSON.stringify([favoriteJobsViewed[i]]);
      localStorage.setItem('viewed_jobs', jobsViewed)
    }
  }

  
  $('.favoriteButton').not('.hiddenD').show();
  
  $('.jobDetailsFavoriteButton').show();

}
