suggested source script

var getLocation = function(href) {
  var l = document.createElement("a");
  l.href = href;
  return l;
};


function addSuggestedSource(suggestedSourceField,userId, company, topic) {
  var encodedCompany = encodeURIComponent(company);
  var encodedTopic = encodeURIComponent(topic);
  var url = "http://mklab.iti.gr/wikirate-sandbox/api/index.php/recommendations/?company=" + encodedCompany + "&topic=" + encodedTopic + "&user_id=" + userId;

  var jqxhr = $.getJSON(url)
    .done(function(data) {
      $.each(data.results, function(i, item) {
        $('#loading_gif').hide();
        var $row = $("<div>", {
          class: "suggested-source-item"
        });
        var $imageDiv = $("<div>", {
          class: "source-link-image"
        });
        var $titleDiv = $("<div>", {
          class: "source-link-title"
        });
        var imageSrc = "";
        if (item.images.length > 0)
          imageSrc = item.images[0].url;
        else
          imageSrc = "https://wikirate-production-storage.fra1.cdn.digitaloceanspaces.com/files/4558/12604318-small.png"
        var $image = $('<img src="' + imageSrc + '">'); 
        $imageDiv.append($image);
        var website = getLocation(item.url).hostname;
//http://127.0.0.1:3000/?card[type]=Page&url=http://www.theguardian.com/commentisfree/2006/jun/13/comment.oil&view=preview&layout=source%20preview%20page%20layout&company=BP&topic=Consumer%20and%20Product%20Responsibility
        var $title = $('<a class="preview-page-link" href="/?card[type]=Page&view=preview&layout=source preview page layout&url=' + encodeURIComponent(item.url) + '&company=' + encodedCompany + '&topic=' + encodedTopic + '" target="_blank"> ' + item.title + ' - ' + website + ' </a>');
        $titleDiv.append($title);
        $row.append($imageDiv);
        $row.append($titleDiv);
        suggestedSourceField.append($row);

      });
    })
    .fail(function(xhr, ajaxOptions, thrownError) {
      suggestedSourceField.html("Fail to get suggested sources.");
       console.log("error with "+xhr.responseText);
    });
   
}
$(document).ready(function() {
  var company = $('#company-key-name').html();
  var topic = $('#topic-key-name').html();
  var userId = $("#user-id").html();
  

  $(".STRUCTURE-source_link_preview").each(function() {
    $(this).find('img').each(function() {
      if ($(this).attr('src') == "") {
        $(this).attr('src', "https://wikirate-production-storage.fra1.cdn.digitaloceanspaces.com/files/4558/12604318-small.png");
      }
    })
  });

  var $suggested_source = $(".suggested-source:first");
if($suggested_source.length>0)
  addSuggestedSource($suggested_source,userId, company, topic);

});