﻿(function() {

  function HABgetElementsByClassName(searchClass, node, tag) {
    var classElements = new Array();
    if (node == null)
      node = document;
    if (tag == null)
      tag = '*';
    var els = node.getElementsByTagName(tag);
    var elsLen = els.length;
    var pattern = new RegExp("(^|\\s)" + searchClass + "(\\s|$)");
    for (i = 0, j = 0; i < elsLen; i++) {
      if (pattern.test(els[i].className)) {
        classElements[j] = els[i];
        j++;
      }
    }
    return classElements;
  }

  function HABRemoveHashTag(URL) {
    if (URL.hash.length > 0) {
      URL = URL.href.substr(0, URL.href.length - URL.hash.length);
      return URL;
    }
    return URL.href;
  }

  function HABFindPosts() {
    var arResult = [];

    var arPosts = HABgetElementsByClassName("Home_ArticleSummaryContainer", document, "div");
    if (arPosts.length > 0) { return arResult; } // We're in the home page, we don't want to add widget here


    arPosts = HABgetElementsByClassName("ArticleContainer", document, "div");
    var elPost, i, elTitle, href, elInsertBefore;

    for (i = 0; i < arPosts.length; i++) {
      elPost = arPosts[i];

      href = HABRemoveHashTag(window.location); // I can't take the link from the title easily. Since we're definitely on a post page, I can just take it from the window.
      elInsertBefore = HABgetElementsByClassName("ArticleFooter", elPost.parentNode, "div")[0];

      arResult.push([href, elInsertBefore]);
    }

    return arResult;
  }

  function GenerateUniqueID() {
    var UniqueID, UniqueIDFound;
    UniqueIDFound = true;
    while (UniqueIDFound) {
      UniqueID = "HAB" + String(Math.floor(Math.random() * 100000));
      UniqueIDFound = document.getElementById(UniqueID);
    }
    return UniqueID;
  }

  var HABPosts = HABFindPosts();
  var i, UniqueID;


  for (i = 0; i < HABPosts.length; i++) {
    UniqueID = GenerateUniqueID();
    var elUniqueDiv = document.createElement("div");
    elUniqueDiv.setAttribute("id", UniqueID);
    HABPosts[i][1].parentNode.insertBefore(elUniqueDiv, HABPosts[i][1]);

    document.write(unescape("%3Cscript src='" + document.location.protocol + "//hearablog.com/widget.js?PermaLink=" + escape(escape(HABPosts[i][0])) + "&elTarget=" + UniqueID + "' type='text/javascript'%3E%3C/script%3E"));
  }

})();