$(document).ready(function () {

  $("#input-job").click(function() {
    chrome.storage.local.get(['login'],function(e){
      if(e.login === undefined || !e.login || e.login == '' ){
        $('button.close').click()
        $('.login-link').click()
        return false
      }else{
         $("#job-modal").modal("show");
      }
    })
  });

  $("#input-post").click(function() {
    chrome.storage.local.get(['login'],function(e){
      if(e.login === undefined || !e.login || e.login == '' ){
        $('button.close').click()
        $('.login-link').click()
        return false
      }else{
         $("#post-modal").modal("show");
      }
    })
  });

  $("#input-event").click(function() {
    chrome.storage.local.get(['login'],function(e){
      if(e.login === undefined || !e.login || e.login == '' ){
        $('button.close').click()
        $('.login-link').click()
        return false
      }else{
         $("#event-modal").modal("show");
      }
    })
  });



  $(document).on('click', '.add-job-thumbnail-btn', function() {
    $('.add-job-thumbnail').click();
  });

  $('.add-job-thumbnail').change(function(){
      var file = this.files[0];
      $('.thumnail-job-preview').attr('src',URL.createObjectURL(file))
      $('.thumnail-job-preview').show()
      $('.remove-image').show()
  });


  $('.remove-image').click(function() {
    $('.add-job-thumbnail').val(''); 
    $('.thumnail-job-preview').attr('src', '').hide(); 
    $('.remove-image').hide()
  });
  
$(document).on('click', 'img.open-job', function(){
  let jobid = $(this).closest('.post').attr('data-job-id');
  if($(this).closest('.post').hasClass('job-item')){
    getOneJob(jobid)
   getMightLikeJob();
  }
});

$(document).on('click', 'p.open-job, .read-all p', function(){
  $(this).closest('.post').find('img.open-job').eq(0).click()
})


$(document).on('click', '.bookmark-job-btn img', function(){
  let jobid = $(this).closest('.post').attr('data-job-id');
 
  chrome.storage.local.get(['login'],function(e){
    
    if(e.login === undefined || !e.login || e.login == '' ){
      $('button.close').click()
      $('.login-link').click()
      return false
    }else{

    pn('Sending request...', 'warning')
    $.ajax({
    method: "GET",
    url: endpoint+'addjobbookmark?id='+jobid,
    headers: {"Authorization": "Bearer " + e.login},
    success: function(serverResponse, txtStatus, request) {
      if(serverResponse.status == true){
          let rpostid = serverResponse.id;
          if(serverResponse.message.indexOf('added') > -1){
            $(`.post[data-job-id="${rpostid}"]`).find('.bookmark-job-btn').html(bookmarkImages[1])
          }else{
            $(`.post[data-job-id="${rpostid}"]`).find('.bookmark-job-btn').html(bookmarkImages[0])
          }
          chrome.runtime.sendMessage({prefeed:true});
          $('.tooltip.bs-tooltip-bottom').removeClass('show');
          $('[data-toggle="tooltip"]').tooltip();
          pn(serverResponse.message, 'success')
        }else{
          pn(serverResponse.message, 'error')
        }
    },
        statusCode: {
        500: function(serverResponse) {
        
          },
        401:function(){
      
        }, 
        422:function(e){

        }
      }
    });
  }
})

});

$(document).on('click', '.job-save-btn', function() {

  chrome.storage.local.get(['login'],function(e){

    if(e.login === undefined || !e.login || e.login == '' ){
      $('button.close').click()
      $('.login-link').click()
      return false
    }else{
  
  let title = $(".td-job input[name='title']").val().trim(); 
  let content = $(".td-job textarea[name='content']").val().trim(); 
  
  let authorName = $(".td-job input[name='author_name']").val().trim(); 
  let image_url = $(".td-job input[name='image_url']").val().trim(); 
  let salary_range = $(".td-job input[name='salary_range']").val().trim(); 
  let company_name = $(".td-job input[name='company_name']").val().trim(); 
  //let ex_months = $(".td-job input[name='ex_months']").val().trim(); 
  let ex_years = $(".td-job input[name='ex_years']").val().trim(); 
  let end_date = $(".td-job input[name='end_date']").val().trim(); 
  let total_vacancy = $(".td-job input[name='total_vacancy']").val().trim(); 

  let city = $(".td-job input[name='city']").val().trim(); 
  let country = $(".td-job input[name='country']").val().trim(); 
  let job_mode = $(".td-job input[name='job_mode']:checked").val().trim(); 

  let external_label_link = $(".td-job input[name='external_label_link']").val().trim(); 
  let url = $(".td-job input[name='url']").val().trim();

  if(title == ''){
    $(".td-job input[name='title']").focus()
    return false;
  }

  if(content == ''){
    $(".td-job textarea[name='content']").focus()
    return false;
  }

  if(total_vacancy == ''){
    $(".td-job input[name='total_vacancy']").focus()
    return false;
  }else{
   // total_vacancy = null
  }

  if(salary_range == ''){
    // $(".td-job input[name='total_vacancy']").focus()
    // return false;
  }else{
    salary_range = null
  }

  // if(end_date == ''){
  //   $(".td-job input[name='end_date']").focus()
  //     return false;
  // }
 
  if(city == ''){
    $(".td-job input[name='city']").focus()
      return false;
  }

  if(country == ''){
    $(".td-job input[name='country']").focus()
      return false;
  }

  if(external_label_link == ''){
    $(".td-job input[name='external_label_link']").focus()
      return false;
  }

  if(url == ''){
    $(".td-job input[name='url']").focus()
      return false;
  }

    var formData = new FormData();
    if(typeof $('.td-job .add-job-thumbnail[type=file]')[0].files[0] != 'undefined'){
        formData.append('image', $('.td-job .add-job-thumbnail[type=file]')[0].files[0]);
    }else if(image_url != ''){

    }else{
      // pn('Image is required.', 'error')
      // return false;
    }
    
      formData.append('title',title);
      formData.append('des',content);
      formData.append('author_name',authorName);
      formData.append('external_label_link',external_label_link);
      formData.append('end_date',end_date);
      formData.append('image_url',image_url);
      formData.append('salary_range',salary_range);
      formData.append('company_name',company_name);
      //formData.append('ex_months',ex_months);
      formData.append('ex_years',ex_years);
      formData.append('city',city);
      formData.append('country',country);
      formData.append('job_mode',job_mode);
      formData.append('total_vacancy',total_vacancy);

      formData.append('url',url);
      $('.job-save-btn').text('Please wait').prop('disabled', true);
      $.ajax({
        data: formData,
        type: 'POST',
        contentType: false,
        processData: false,
        url: endpoint+'addnewjobviaext',
        headers: {"Authorization": "Bearer " + e.login},
        success: function(serverResponse, txtStatus, request) {
              $('.job-save-btn').text('Submit For Review').prop('disabled', false)
          if(serverResponse.status == true){              
              pn(serverResponse.message, 'success')
              $('.td-job').trigger("reset");
              $('.thumnail-job-preview').hide()
          }else{
              pn(serverResponse.message, 'error')
          }
        },
        statusCode: {
        500: function(serverResponse) {
        
          },
        401:function(){
      
        }, 
        422:function(e){
    
        }
      }
    });

  }

})
    
})

});


function getMightLikeJob(){
  skeletonloadingformightlike()
        $.ajax({
          method: "GET",
          url: endpoint+'getmightlikejob',
          success: function(serverResponse, txtStatus, request) {
            if(serverResponse.status == true){
              displayMightLikeJob(serverResponse.likefeed)
              } 
          },
          statusCode: {
          500: function(serverResponse) {},
          401:function(){}, 
          422:function(e){}
        }
      });

}


function getOneJob(id){
  addingSkeletonLoadingForFullPost(true)
  chrome.storage.local.get(['login'], function(st){
  $.ajax({
    method: "GET",
    url: endpoint+'getjob?id='+id,headers: {"Authorization": "Bearer " + st.login},
    success: function(serverResponse, txtStatus, request) {
      addingSkeletonLoadingForFullPost(false)  
      if(serverResponse.status == true){
          showSingleJob(serverResponse.job)
        }
    },
    statusCode: {
    500: function(serverResponse) {
    
      },
    401:function(){
  
    }, 
    422:function(e){

    }
  }
});
});
}

function getJobFeed(skip=0){

    $('.all_feeds').hide();
    $('.all_jobs').show();

    if(skip == 0){
     $('.all_feeds').html('')
    }
      
    addingSkeletonLoadingForJobListing(true);
       chrome.storage.local.get(['login'], function(st){
           $('.all_jobs').removeClass('section__popular')
                           .removeClass('section__most-voted')
                           .removeClass('section__best-discussion')
                           .removeClass('section__search')
           $('.all_jobs').addClass('section__'+feedType)
   
           let finalEndPoint = endpoint+'getJobfeed?skip='+skip+'&type='+feedType+'&supp_filter='+supp_filter
           if(feedTypebysearch && $('#search-jobs').val().trim() != ''){
             finalEndPoint = endpoint+'getJobfeed?skip='+skip+'&type='+feedType+'&supp_filter='+supp_filter+'&feedTypebysearch='+feedTypebysearch+'&searchtext='+$('#search-jobs').val().trim().replaceAll(`’`, `'`)
           
             if($('#search-jobs').val().trim() == '<script'){
                addingSkeletonLoadingForJobListing(false);  
               $('.all_jobs').append(noMoreResults)
               return false;
             }
           }
   
           $.ajax({
             method: "GET",
             url: finalEndPoint,
             headers: {"Authorization": "Bearer " + st.login},
             success: function(serverResponse, txtStatus, request) {
                addingSkeletonLoadingForJobListing(false);  
               if(serverResponse.status == true){
                 if(feedType == 'search' && $('#search-jobs').val().trim() != ''){
                  $('.search-for').show().text('Search results for \"'+$('#search-jobs').val().trim()+'\"')
                 }else{
                   $('.search-for').hide()
                 }  
                 let feed = serverResponse.feed;
                   if(feed.length){
                     addItemIntoJobFeed(feed);
                   }else{
                     if(!$('.no-more-row').length){
                       $('.all_jobs').append(noMoreResults)
                     }
                   }
                 }
             },
             statusCode: {
             500: function(serverResponse) {
             
               },
             401:function(){
           
             }, 
             422:function(e){
         
             }
           }
         });
       })
   
   
   }


//    let loadedPosts = -1;
function addItemIntoJobFeed(feed){
  if(supp_filter != -1){
  
      feed.forEach(element => {
          let item = prePareJobHtml(element,  'not-sponsored');
        
          if(!$('div.job[data-job-id="'+element.id+'"]').length){
            if(element.is_pin == 1){
           //  $('.all_jobs').prepend(item)
            }else{
              $('.all_jobs').append(item)
            }
          }
      });
     // checkForSponsoredJob(st)
   
   // addTitles();
  }
}


function prePareJobHtml(element, extraClasses){
    let item = '';
   
    let isBookMark = bookmarkImages[0];
    if(element.isBookMark != null){
      isBookMark = bookmarkImages[1];
    }
  
    let thumbnail = element.company_logo;
    let external_label_link =  (element.external_label_link == null)? 'Read Article':element.external_label_link;
    let redirectlabel = ` <span class="read_feed redirect-link" style="display:none">
    <a target="_blank" href="${element.url}" >
    <u>${external_label_link}</u>
    <img src="../assets/images/view.svg">
    </a>
    </span>`
   
  
    let title = JSON.parse(element.title);
  
  
      if(title.length>69){
        title = JSON.parse(element.title).substring(0,69)+'...'
      }
  
        let IsPinLabel = ``;
  
        if(element.is_pin == 1){
          IsPinLabel = `<span class="pinned-post-parent"><img class="pinned-post" src="${pinnedImageUrl}">Pinned post</span>`;
        }
  
        if(element.is_sponsored == 1){
          IsPinLabel = `<span class="pinned-post-parent"><img class="pinned-post" src="${sponsoredPostImageUrl}">Sponsored</span>`;
        }

        let hoverText =  ``;
        let blackTheme = ''
        let whiteThemeClass = ''
        let company_logo_class = ''
        if(thumbnail == null){
          whiteThemeClass = 'dancing-class'
             thumbnail = '../assets/images/white.png'
             blackTheme =   `<img data-toggle="modal" data-target="#myJobModal" class="${whiteThemeClass} thumbnail-image open-job black-theme-thumbnail" src="../assets/images/black.png"></img>`
  
             hoverText =  `<span class="two-ch-center">${title.substring(0, 2)}</span>`;
        }else{
            company_logo_class = 'company-logo'
        }

        let jobLocation = '';

        if(element.city ==null || element.country == null){
          jobLocation = 'd-none';
        }

        let deadline = ''

        if(element.end_date != null){
          deadline = `<div class="job-attributes">
            <img data-toggle="tooltip" data-placement="bottom" title="Deadline Date" class="sup-favicon-1" src="../assets/images/calendar.png">
            <span class="job-date-time mr-2">${displayDate(element.end_date)}</span>
          </div>`;
        }
  
        item = `<div data-supplier-id="${element.supplier_id}" data-job-id ="${element.id}" class="row feed_strip post job-item feed_full_width ${extraClasses} " >
        ${IsPinLabel}
        <div class="col-2">
        ${hoverText}
              <img data-toggle="modal"  class="open-job ${whiteThemeClass} white-theme-thumbnail ${company_logo_class}" data-target="#myJobModal" src="${thumbnail}">
              ${blackTheme}
              </div>
              <div class="col-10 feed_icon">
              <p   class="open-job tooltip-r post-title" data-toggle="tooltip" data-placement="bottom" title="${JSON.parse(element.title)}">${title}</p>
             
            

               <div class="job-attributes">
                <img data-toggle="tooltip" data-placement="bottom" title="Company name" class="sup-favicon-1" src="../assets/images/job/company-icon.png">
                <span class="job-date-time mr-2">${element.company_name}</span>
              </div>
              
               <div class="job-attributes ${jobLocation}">
                <img data-toggle="tooltip" data-placement="bottom" title="Location" class="sup-favicon-1" src="../assets/images/location.png">
                <span class="job-date-time mr-2">${element.city}, ${element.country}</span>
              </div>

               <div class="job-attributes">
                <img data-toggle="tooltip" data-placement="bottom" title="Required Experience" class="sup-favicon-1" src="../assets/images/job/company-icon-ex.png">
                <span class="job-date-time mr-2">${displayEx(element.ex_years)}</span>
              </div>

              <br>
              <div class="job-attributes">
                <img data-toggle="tooltip" data-placement="bottom" title="Job type" class="sup-favicon-1" src="../assets/images/dollar.png">
                <span class="job-date-time mr-2">${element.job_mode}</span>
              </div>


              <span class="post-author"><img src="${authorFaviConUrl(element.display_author_logo, element.author_logo)}" class="author-image">${(element.display_author_name == null) ? JSON.parse(element.author_name): element.display_author_name}</span>
            
              <span class="pills bookmark-job-btn" id="msg_icon">
                  ${isBookMark}
                </span>
              <span class="pills share-icons" id="share_icon" style="display:none">
                  <img class="share-default" src="../assets/images/share_icon.png">
                  <img class="green-share" src="../assets/images/green-share.png">
              </span>
              ${redirectlabel}
             
          </div>
        </div>`; 
    
  
    return item;
  }

  function displayEx(input) {
    if (input.includes('-')) {
      return input + ' years';
  } else {
      let yearValue = parseFloat(input);
      let formattedValue = yearValue === 1 ? '1 year' : yearValue.toFixed(1).replace('.0', '') + ' years';
      return formattedValue;
  }
}

  function showSingleJob(job){
    let jobObj = job[0];
  
    let des = parseDes(jobObj.description);
  
    let thumbnail = "../assets/images/feed-def-image.png";
    let external_label_link =  (jobObj.external_label_link == null)? 'Read Article':jobObj.external_label_link;
    let readlabel = '<button class="redirect-for-read">'+external_label_link+' <img src="../assets/images/view1.png" class="view1 read-full-aritcle"></button>';
    thumbnail = jobObj.company_logo;
    let facebookShare = `https://www.facebook.com/sharer/sharer.php?display=page&u=${jobObj.url}`;
    let twitterShare =  `https://twitter.com/share?text=${encodeURI(JSON.parse(jobObj.title))}&url=${jobObj.url}&via=TestingDaily`;
    let deadline = ''
    if(jobObj.end_date != null){
      deadline = ` <div class="col-md-6">
            <img data-toggle="tooltip" data-placement="bottom" title="Deadline date" class="sup-favicon-1" src="../assets/images/calendar.png">
            <span class="post-date-time">${displayDate(jobObj.end_date)}</span>
        </div>`;
    }

    let total_vacancy = ''

    if(jobObj.total_vacancy != 0){
      total_vacancy=  `<span class="event-duration">
            <img data-toggle="tooltip" data-placement="bottom" title="Number of openings" src="../assets/images/job/total-openings.png" class="job-duration-image">
        <span class="detail-page-attr">${jobObj.total_vacancy}</span>
      </span>`
    }


    let hoverText =  ``;
    let  whiteThemeClass = ''
	  let blackTheme = ''
    if(thumbnail == null){
		whiteThemeClass = 'dancing-class'
         thumbnail = '../assets/images/white.png'
		 blackTheme =   `<img class="full-post-thumbnail ${whiteThemeClass} black-theme-thumbnail" src="../assets/images/black.png">`

         hoverText =  `<span class="two-ch-center">${JSON.parse(jobObj.title).substring(0, 2)}</span>`;
    }


    let thumbnailHtml = `${hoverText}<img class="full-post-thumbnail ${whiteThemeClass} white-theme-thumbnail" src="${thumbnail}">${blackTheme}`

    $('.full-job').html(`<div  id="demo" class="carousel slide " data-ride="carousel">
    <div class="carousel-inner">
     ${thumbnailHtml}
    </div>
    
    </div>
    <div data-job-id ="${jobObj.id}"  class="col-12 feed_modal job">
     <p class="tooltip-r" data-toggle="tooltip" data-placement="bottom" title="${JSON.parse(jobObj.title)}">${JSON.parse(jobObj.title)}</p>
    
        
        <div class="row">
  
      

        <div class="col-md-6">
            <img data-toggle="tooltip" data-placement="bottom" title="Company name" class="sup-favicon-1" src="../assets/images/job/company-icon.png">
            <span class="post-date-time">${jobObj.company_name}</span>
        </div>
        <div class="col-md-6">
            <span class="event-duration">
                  <img data-toggle="tooltip" data-placement="bottom" title="Company location" src="../assets/images/job/location.png" class="job-duration-image">
                  <span class="detail-page-attr">${jobObj.city},${jobObj.country}</span>
            </span>
        </div>

      </div>
  
     
  
      <div class="row mt-1">
        <div class="col-md-6">
            <span data-toggle="tooltip" data-placement="bottom" title="Author" class="post-author"><img src="${authorFaviConUrl(jobObj.display_author_logo, jobObj.author_logo)}" class="author-image">${(jobObj.display_author_name == null) ? JSON.parse(jobObj.author_name): jobObj.display_author_name}</span>
        </div>

         <div class="col-md-6">
            <img data-toggle="tooltip" data-placement="bottom" title="Job type" class="sup-favicon-1 job-type-d" src="../assets/images/dollar.png">
            <span class="post-date-time">${jobObj.job_mode}</span>   
          </div>
      </div>

       <div class="row mt-1">
         <div class="col-md-6">
            <img data-toggle="tooltip" data-placement="bottom" title="Required Experience" class="sup-favicon-1 job-type-d" src="../assets/images/job/company-icon-ex.png">
            <span class="post-date-time">${displayEx(jobObj.ex_years)}</span>   
          </div>
      </div>



      
     <p class="feed_p">${des}</p>
    
     <div class="row">
       <a href="${(jobObj.url)}" target="_blank">
        ${readlabel}
     </a>
     </div>
    
      <span class="pills open-share-options" id="share_icon"><img src="../assets/images/share_icon.png"></span>
    
     <ul class="social_icons">
     <h6 style="font-weight: 400;font-size: 18px;line-height: 24px;color: #4D4D4D;margin-top:8px">Share Article</h6>
  
      <img data-copy-url="${job.url}" class="social-img copy-post-url" src="../assets/images/copy.png"></img>
      <a href="whatsapp://send?text=The text to share!" data-action="share/whatsapp/share">
        <img class="social-img" src="../assets/images/whatsapp.png"></img>
      </a>
      <a href="${facebookShare}" target="_blank"><img class="social-img" src="../assets/images/facebook.png"></img></a>
      <a href="${twitterShare}" target="_blank"><img class="social-img" src="../assets/images/twitter.png"></img></a>
      
     </ul>
      
    </div>`);
  }

  function getPinJob(){

    chrome.storage.local.get(['login'], function(st){
  
        $.ajax({
          method: "GET",
          url: endpoint+'getPinJobExt',
          headers: {"Authorization": "Bearer " + st.login},
          success: function(serverResponse, txtStatus, request) {
     
            if(serverResponse.status == true && serverResponse.feed.length){ 
              let feed = serverResponse.feed;
                 addItemIntoFeedForJob(feed)
              }
          },
          statusCode: {
          500: function(serverResponse) {
          
            },
          401:function(){
        
          }, 
          422:function(e){
      
          }
        }
      });
    })
  
  
  }

  function addItemIntoFeedForJob(feed){
        feed.forEach(element => {
            let item = prePareJobHtml(element,  'not-sponsored');
            console.log(item)
            if(!$('div.job[data-job-id="'+element.id+'"]').length){
              if(feedType == 'bookmark'){
                $('.all_jobs').prepend(item)
              }else if(element.is_pin == 1){
               $('.all_jobs').prepend(item)
              }else{
                $('.all_jobs').append(item)
              }
            }else{
                console.log('already')
            }
        });
      //  checkForSponsoredEvent()
     
       // addTitles();
    // }
  }

  
 