titleSanitization = function(text) {
  return text.replace("<", "lt").replace(">", "gt").replace("&", "amp").replace('"', "quot").replace("'", "x27").replace("/", "x2F").replace("\\", "backslash").replace("script", "nie zycze tego").replace("onclick", "nie zycze tego");
} //zabezpieczenie przed xssem, troche nadgorliwe ale jest

parseSites = function(url) {
  var ytApiKey = "AIzaSyDWxOr4Li4A6HtYx9k7bVbCQ68vpwJJuoc";
  /*kod autoryzacji zydrury, swoja droga ten jest zajebany ze skryptu youtube link title, takze nie gwarantuje dzialania xD ale powinien */
  var cc = new XMLHttpRequest();
  if (url.indexOf("dailymotion") > -1) {
    cc.open("GET", url.replace(/https:\/\/www\.dailymotion\.com\/video\/([^&]+)/g, "https://api.dailymotion.com/video/\$1?fields=duration,thumbnail_url,title,owner.username"), false);
    cc.send();
    var jsonth = JSON.parse(cc.responseText);
    return {
      thumb: jsonth.thumbnail_url,
      duration: jsonth.duration,
      title: titleSanitization(jsonth.title),
      channelTitle: titleSanitization(jsonth["owner.username"])
    };
  } else if (url.indexOf("vimeo") > -1) {
    cc.open("GET", url.replace(/https:\/\/vimeo\.com\/([^&]+)/g, "https://vimeo.com/api/oembed.json?url=https://vimeo.com/\$1"), false);
    cc.send();
    var jsonth = JSON.parse(cc.responseText);
    return {
      thumb: jsonth.thumbnail_url,
      duration: jsonth.duration,
      title: titleSanitization(jsonth.title),
      channelTitle: titleSanitization(jsonth.author_name)
    };
  } else if (url.indexOf("youtube") > -1) {
    var youtubeID = url.replace(/https:\/\/www\.youtube\.com\/watch\?v=([^]+)/g, "\$1");
    var youtubeAPIUrl = `https://www.googleapis.com/youtube/v3/videos?part=contentDetails,snippet&id=${youtubeID}&key=${ytApiKey}&fields=items(snippet(title,channelTitle),contentDetails(duration))`;
    cc.open("GET", youtubeAPIUrl, false);
    cc.send();
    var jsonth = JSON.parse(cc.responseText).items[0];
    try {
      return {
        title: titleSanitization(jsonth.snippet.title),
        duration: jsonth.contentDetails.duration, //czas trwania zwracany jest w postaci zgodnej z ISO 8601, w sensie PTXXXHXXMXXS
        channelTitle: titleSanitization(jsonth.snippet.channelTitle)
      };
    }
    catch (TypeError) {
      return undefined;
    }
  }
}
duration = function(sec) {
  if (sec >= 3600) {
    var hours = Math.floor(sec / 3600);
    var minutes = Math.floor((sec - 3600 * hours) / 60);
    var seconds = sec - hours * 3600 - minutes * 60;
    return `(${hours}h${minutes}m${seconds}s)`;
  } else if (sec < 3600 && sec > 60) {
    var minutes = Math.floor(sec / 60);
    var seconds = sec - minutes * 60;
    return `(${minutes}m${seconds}s)`;
  } else {
    return `(${sec}s)`;
  }
}
youtubeDurationConverter = function(time) {
  var timeArray = time.match(/(\d+)/g);
  if (timeArray.length == 3) {
    return `(${timeArray[0]}h${timeArray[1]}m${timeArray[2]}s)`;
  } else if (timeArray.length == 2) {
      if (time.indexOf("H") == -1) {
        return `(${timeArray[0]}m${timeArray[1]}s)`;
      } else if (time.indexOf("H") > -1 && time.indexOf("M") > -1) {
        return `(${timeArray[0]}h${timeArray[1]}m`;
      } else {
        return `(${timeArray[0]}h${timeArray[1]}s`;
      }
  } else if (timeArray.length == 1) {
      if (time.indexOf("H") > -1) {
        return `(${timeArray}h)`;
      } else if (time.indexOf("M") > -1) {
        return `(${timeArray}m)`;
      } else {
        return `(${timeArray}s)`;
      }
  }
}
embedFix = function() {
  var sites = {
    youtube: true,
    vimeo: true,
    dailymotion: true,
    pornhub: true,
    liveleak: true
  };
  $("a.fileThumb").has("iframe").each(function() {
    var href = $(this).find("iframe").attr("src");
    var fid = $(this).parent(".file").attr("id");
    if (href.indexOf("youtube") > -1 && sites.youtube === true) {
            href = href.replace("embed/", "watch?v=");
      var ytInfo = parseSites(href);
      if (Boolean(ytInfo) === true) { 
        var ytdur = youtubeDurationConverter(ytInfo.duration);
        var ytMovieID = href.replace(/https:\/\/www\.youtube\.com\/watch\?v=([^]+)/g, "\$1");
        $(this).parent(".file").find("span.fileText").replaceWith(`<span class="fileText" id="${fid}"><a class="emblink${fid}" target="_blank" href="${href}">Embed</a>: ${titleSanitization(ytInfo.title)}, uploaded by: ${titleSanitization(ytInfo.channelTitle)}, ${ytdur}</span>`);
      } else {
        $(this).parent(".file").find("span.fileText").replaceWith(`<span class="fileText" id="${fid}"><a class="emblink${fid}" target="_blank" href="${href}">Embed</a>: Film niedostepny (prywatny bądź usuniety).</span>`); //dla starych nitek na mu
      }
    }  else if (href.indexOf("dailymotion") > -1 && sites.dailymotion === true) {
      href = href.replace("/embed/", "/");
      var dmInfo = parseSites(href)
      var dmdur = duration(dmInfo.duration);
      var dmres = `(${dmInfo.width}x${dmInfo.height})`
      $(this).parent(".file").find("span.fileText").replaceWith(`<span class="fileText" id="${fid}"><a class="emblink${fid}" target="_blank" href="${href}">Embed</a>: ${titleSanitization(dmInfo.title)}, uploaded by: ${titleSanitization(dmInfo.channelTitle)}, ${dmdur}</span>`);
    } else if (href.indexOf("vimeo") > -1 && sites.vimeo === true) {
      href = href.replace(/https:\/\/player\.vimeo\.com\/video\/([^&]+)/g, "https://vimeo.com/\$1");
      var vimeoInfo = parseSites(href)
      var vdur = duration(vimeoInfo.duration);
      $(this).parent(".file").find("span.fileText").replaceWith(`<span class="fileText" id="${fid}"><a class="emblink${fid}" target="_blank" href="${href}">Embed</a>: ${titleSanitization(vimeoInfo.title)}, uploaded by: ${titleSanitization(vimeoInfo.channelTitle)}, ${vdur}</span>`);
    } else if (href.indexOf("pornhub") > -1 && sites.pornhub === true) {
      href = href.replace("embed/", "view-video.php?key=");
      $(this).parent(".file").find("span.fileText").replaceWith(`<span class="fileText" id="${fid}">Embed: <a class="emblink${fid}" target="_blank" href="${href}">PornHub</a></span>`);
    } else if (href.indexOf("liveleak") > -1 && sites.liveleak === true) {
      href = href.replace("e/", "view?t=");
      $(this).parent(".file").find("span.fileText").replaceWith(`<span class="fileText" id="${fid}">Embed: <a class="emblink${fid}" target="_blank" href="${href}">LiveLeak</a></span>`);
    }
  })
};
embedFix();
if (localStorage.getItem("o_loader") == 1 || $(".postingMode").length != 0) {
  $(document).ajaxComplete(function() {
    embedFix();
  })
}