var sponsoredEvent = []
var repeat_after_y = 0;
getSponsoredEvent()


function displayEventDate(dt, timeKey){
  var myDate = new Date(dt);
  let timeString = ''
  if(timeKey){
    timeString = ' ('+timeKey+')'
  }

  let dateNewFormat = moment(myDate).format("MMM DD, YYYY hh:mm A");
  if(dt.indexOf('00:00:00')>-1){
    dateNewFormat = moment(myDate).format("MMM DD, YYYY");
  }
  return dateNewFormat+timeString;
  }


function getEventFeed(skip=0){
  $('.all_feeds').show()
  $('.all_jobs').hide()
    // feedType = (feedType != 'bookmark') ? 'latest':'bookmark';
    if(skip == 0){
     $('.all_feeds').html('')
    }
     if(loadedPosts != skip || skip ==0){
       loadedPosts = skip;

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


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


  function prePareEventHtml(element,  extraClasses){
    let item = '';

    let isBookMark = bookmarkImages[0];
    if(element.isBookMark != null){
      isBookMark = bookmarkImages[1];
    }

    let thumbnail = "../assets/images/feed-def-image.png";
    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>`
  
    if (element.supplier_id == 2){
      thumbnail = element.image; 
      redirectlabel = ` <span class="read_feed redirect-link youtube-redirect" style="display:none; ">
                      <a target="_blank" href="${element.url}" >
                      <u>Watch on youtube</u>
                      <img src="${faviConUrl(element.supplier_id, element.display_author_logo)}">
                      </a>
                      </span>`
    }else if(element.supplier_id == 3){
      thumbnail = '../assets/images/feed-def-image.png'
    }else{
      thumbnail = element.image
    }
   
  
    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 event</span>`;
        }else{
        }
  
        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>`;
        }
       
        let is_paid = ''
        if (element.is_paid) {
          is_paid = ` <span class="event-duration">
              <img src="../assets/images/dollar2.png" class="event-duration-image">
              <span class="event-attr">${(element.is_paid == 1)?'Paid':'Free'}</span>
              </span>`
        }
  
        item = `<div data-supplier-id="${element.supplier_id}" data-post-id ="${element.id}" class="row feed_strip post event-item feed_full_width ${extraClasses} " >
        ${IsPinLabel}
        <div class="col-2">
        ${hoverText}
              <img data-toggle="modal"  class="open-post  white-theme-thumbnail" data-target="#myModal" src="${thumbnail}">
             
              </div>
              <div class="col-10 feed_icon">
              <p   class="open-post tooltip-r post-title" data-toggle="tooltip" data-placement="bottom" title="${JSON.parse(element.title)}">${title}</p>
             
              <img data-toggle="tooltip" data-placement="bottom" title="Event Date & Time" class="sup-favicon-1" src="../assets/images/calendar.png">
              <span class="post-date-time">${displayEventDate(element.start_date, element.time_zone)}</span>
              <span class="event-duration">
                    <img src="../assets/images/timer.png" class="event-duration-image">
                    <span class="event-attr">${durationDiff(element.start_date, element.end_date)}</span>
              </span><br>

              <span class="event-duration">
              <img src="../assets/images/location.png" class="event-duration-image">
                <span class="event-attr">${eventLocation(element.event_mode, element.city, element.country)}</span>
              </span>

             ${is_paid}

              <span class="pills bookmark-event-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;
  }

  eventLocation =(eventMode, city, country) =>{

    if(eventMode == '1'){
      return 'Online'
    }else{
      return city+', '+country;
    }
  }
  durationDiff = (s,d) =>{
    const date1 = moment(s);
    const date2 = moment(d);
    const diff = moment.duration(Math.abs(date2.diff(date1)));
    let days = Math.floor(diff.asDays());
    let hours = diff.hours();
    let Mins = diff.asMinutes();
    let daysText = '';
    if (days !== 0) {
        daysText = days + (days > 1 ? ' Days ' : ' Day ');
    }
    let hoursText = hours + (hours > 1 ? ' Hours ' : ' Hour ');

    if(days!==0 && hours > 0){
       days = days+1;
       daysText = days + ' Days ';
       hoursText = ''
    }

    if(days ==0 && hours ==0){
      return Mins +' Minutes'
    }

    if(hours==0){hoursText=''}
    
    return daysText + hoursText;
  }
  function getOneEvent(id){
    addingSkeletonLoadingForFullPost(true)
    chrome.storage.local.get(['login'], function(st){
    $.ajax({
      method: "GET",
      url: endpoint+'getevent?id='+id,headers: {"Authorization": "Bearer " + st.login},
      success: function(serverResponse, txtStatus, request) {
        addingSkeletonLoadingForFullPost(false)  
        if(serverResponse.status == true){
            showSingleEvent(serverResponse.event)
          }
      },
      statusCode: {
      500: function(serverResponse) {
      
        },
      401:function(){
    
      }, 
      422:function(e){
  
      }
    }
  });
  });
  }


  function showSingleEvent(event){
	post = event[0]

	let des = parseDes(post.description);

	let thumbnail = "../assets/images/feed-def-image.png";
	let external_label_link =  (post.external_label_link == null)? 'Read Article':post.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>';
	
	 if (post.supplier_id == 2){
	  thumbnail = post.image; //parseThumbnail(post.image, post.supplier_id, 'single_post');
	  readlabel = `<button class="redirect-for-read youtube-watch-btn">Watch on youtube<img src="${faviConUrl(post.supplier_id, post.display_author_logo)}" class="view1 read-full-aritcle"></button>`;
	}else  if (post.supplier_id == 3){

	}else{
		thumbnail = post.image;
	}

 

	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(post.title).substring(0, 2)}</span>`;
    }
  
	let facebookShare = `https://www.facebook.com/sharer/sharer.php?display=page&u=${post.url}`;
	let twitterShare =  `https://twitter.com/share?text=${encodeURI(JSON.parse(post.title))}&url=${post.url}&via=TestingDaily`;

	let thumbnailHtml = `${hoverText}<img class="full-post-thumbnail white-theme-thumbnail" src="${thumbnail}">`
	
  let is_paid = ''
  if (post.is_paid) {
    is_paid = ` <span class="event-duration">
        <img src="../assets/images/dollar2.png" class="event-duration-image">
        <span class="event-attr">${(post.is_paid == 1)?'Paid':'Free'}</span>
        </span>`
  }

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

      <div class="col-md-6">
          <img data-toggle="tooltip" data-placement="bottom" title="Event Start Date & Time" class="sup-favicon-1" src="../assets/images/calendar.png">
          <span class="post-date-time">${displayEventDate(post.start_date, post.time_zone)}</span>
      </div>
      <div class="col-md-6">
          <img data-toggle="tooltip" data-placement="bottom" title="Event End Date & Time" class="sup-favicon-1" src="../assets/images/calendar.png">
          <span class="post-date-time">${displayEventDate(post.end_date, post.time_zone)}</span>
      </div>
    </div>

    <div class="row mt-1">

      <div class="col-md-6">

          <span class="event-duration">
                      <img src="../assets/images/timer.png" class="event-duration-image">
                  <span class="detail-page-attr">${durationDiff(post.start_date, post.end_date)}</span>
          </span>
      </div>
      <div class="col-md-6">
          <span class="event-duration">
                <img src="../assets/images/location.png" class="event-duration-image">
                <span class="detail-page-attr"> ${eventLocation(post.event_mode, post.city, post.country)}</span>
          </span>
      </div>
    </div>

    <div class="row mt-1">

  ${is_paid}

      <div class="col-md-6">
          <span class="post-author"><img src="${authorFaviConUrl(post.display_author_logo, post.author_logo)}" class="author-image">${(post.display_author_name == null) ? JSON.parse(post.author_name): post.display_author_name}</span>
      </div>
    </div>
    
   <p class="feed_p">${des}</p>
	
	 <div class="row">
	   <a href="${(post.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="${post.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 getMightLikeEvent(){
  skeletonloadingformightlike()
        $.ajax({
          method: "GET",
          url: endpoint+'getmightlikeevent',
          success: function(serverResponse, txtStatus, request) {
            if(serverResponse.status == true){
               displayMightLikeEvent(serverResponse.likefeed)
              } 
          },
          statusCode: {
          500: function(serverResponse) {},
          401:function(){}, 
          422:function(e){}
        }
      });

}

function getPinEvent(){

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

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


}

$(document).ready(function(){

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

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

  $(document).on('click', '.event-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-event input[name='title']").val().trim(); 
    let content = $(".td-event textarea[name='content']").val().trim(); 
    
    let authorName = $(".td-event input[name='author_name']").val().trim(); 
    let image_url = $(".td-event input[name='image_url']").val().trim(); 
    let start_date = $(".td-event input[name='start_date']").val().trim(); 
    let end_date = $(".td-event input[name='end_date']").val().trim(); 
    let time_zone = $(".td-event input[name='time_zone']").val().trim(); 

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

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

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

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

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

    if (new Date(start_date) >= new Date(end_date)) {
        pn('The start date must be earlier than the end date.', 'error')
        return false;
    }
    
    if(time_zone == ''){
      $(".td-event input[name='time_zone']").focus()
        return false;
    }

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

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

      var formData = new FormData();
      if(typeof $('.td-event .add-event-thumbnail[type=file]')[0].files[0] != 'undefined'){
          formData.append('image', $('.td-event .add-event-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('start_date',start_date);
        formData.append('image_url',image_url);
        formData.append('time_zone',time_zone);

        formData.append('city',city);
        formData.append('country',country);
        formData.append('is_paid',is_paid);
        formData.append('event_mode',event_mode);

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

    }

  })
      
  })

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

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

 
  $('.remove-image').click(function() {
    $('.add-post-thumbnail').val(''); 
    $('.add-event-thumbnail').val(''); 
    $('.thumnail-post-preview').attr('src', '').hide(); 
    $('.thumnail-event-preview').attr('src', '').hide(); 
    $('.remove-image').hide()
});

  $(document).on('click', '.post-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-post input[name='title']").val().trim(); 
    let content = $(".td-post textarea[name='content']").val().trim(); 
    
    let authorName = $(".td-post input[name='author_name']").val().trim(); 
    let image_url = $(".td-post input[name='image_url']").val().trim(); 
    let external_label_link = $(".td-post  input[name='external_label_link']").val().trim(); 
    let url = $(".td-post input[name='url']").val().trim();

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

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

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

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

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

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

    }

  })
      
  })



  $(document).on('click', '.bookmark-event-btn img', function(){
    let postid = $(this).closest('.post').attr('data-post-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+'addeventbookmark?id='+postid,
      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-post-id="${rpostid}"]`).find('.bookmark-event-btn').html(bookmarkImages[1])
            }else{
              $(`.post[data-post-id="${rpostid}"]`).find('.bookmark-event-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){
  
      }
    }
  });


}
    })
    


  });




});


function checkForSponsoredEvent(){
  repeat_after_y  = parseInt(repeat_after_y)

  if(sponsoredEvent.length){
    let all = document.querySelectorAll('.all_feeds div.post[data-post-id]:not(.not-in-loop)');
    
      for(let x=0; x<=all.length; x = x+repeat_after_y){
        if(x>0  && x <=  all.length-1){
          sponsoredEvent.forEach(element => {
              let xptx = prePareEventHtml(element, 'sponsored-post');
              if (supp_filter == -1) {
                if($('.sponsored-post').length==0){
                      all[x-1].insertAdjacentHTML('afterend',xptx)
                }else{
                      all[x].insertAdjacentHTML('afterend',xptx)
                }
              }
          });
        }
      }



      $('.all_feeds div.post[data-post-id]:not(.not-in-loop)').addClass('not-in-loop')

      let allXP = document.querySelectorAll('.all_feeds div.post.not-in-loop');
      let initCheck = true;
               
      for( let px = allXP.length-1; px >= 0; px--){
        
        if(allXP[px].classList.contains('sponsored-post')){
          initCheck = false;
        }

        if(initCheck){
          allXP[px].classList.remove('not-in-loop')
        }
       
      }
  }
}


function getSponsoredEvent(){
  chrome.storage.local.get(['login'], function(st){
      $.ajax({
        method: "GET",
        url: endpoint+'getSponsoredEvent',
        headers: {"Authorization": "Bearer " + st.login},
        success: function(serverResponse, txtStatus, request) {
   
          if(serverResponse.status == true && serverResponse.feed.length){ 
            let feed = serverResponse.feed;
              if(feed[0].post_type == 3){
                  //prependPollPost(serverResponse); 
              }else{
              
                  sponsoredEvent = feed
                  repeat_after_y = parseInt(serverResponse.repeat_after_x)


                  if($('.sponsored-post').length==0){
                    checkForSponsoredEvent()
                  }
                    
              } 
            }
        },
        statusCode: {
        500: function(serverResponse) {
        
          },
        401:function(){
      
        }, 
        422:function(e){
    
        }
      }
    });
  })
}