﻿(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("type-post hentry", document, "div");
    var elPost, i, elTitle, href, elInsertBefore;

    for (i = 0; i < arPosts.length; i++) {
      elPost = arPosts[i];

      if (elPost.parentNode.className == "teasers_box") { continue; } // Do not show players in the teasers

      elTitle = elPost.getElementsByTagName("h2")[0];
      if (elTitle) {
        var elLink = elTitle.getElementsByTagName("a")[0];
        if (elLink) {
          href = elTitle.getElementsByTagName("a")[0].href;
        } else {
          href = HABRemoveHashTag(window.location);
        }
      } else {
        href = HABRemoveHashTag(window.location);
      }

      elInsertBefore = HABgetElementsByClassName("sociable", elPost, "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"));
  }

})();
