/* Test if an element has a certain class **************************************
 *
 * Description: Uses regular expressions and caching for better performance.
 * Maintainers: [[User:Mike Dillon]], [[User:R. Koot]], [[User:SG]]
 */
 
var hasClass = (function() {
  var reCache = {};
  return function (element, className) {
    return (reCache[className] ? reCache[className] : (reCache[className] = new RegExp("(?:\\s|^)" + className + "(?:\\s|$)"))).test(element.className);
  };
})();

/** Dynamic Navigation Bars (experimental) **************************************/
 
// set up the words in your language
var NavigationBarHide = '[skrýt ▲]';
var NavigationBarShow = '[zobrazit ▼]';
 
// shows and hides content and picture (if available) of navigation bars
// Parameters:
//     indexNavigationBar: the index of navigation bar to be toggled
function toggleNavigationBar(indexNavigationBar)
{
  var NavToggle = document.getElementById("NavToggle" + indexNavigationBar);
  var NavFrame = document.getElementById("NavFrame" + indexNavigationBar);
  if (!NavFrame || !NavToggle) return false;
  // if shown now
  if (NavToggle.firstChild.data == NavigationBarHide) {
    for (var NavChild = NavFrame.firstChild; NavChild != null; NavChild = NavChild.nextSibling) {
      if (hasClass(NavChild, 'NavContent'))
        NavChild.style.display = 'none';
    }
    NavToggle.firstChild.data = NavigationBarShow;
  // if hidden now
  } else if (NavToggle.firstChild.data == NavigationBarShow) {
    for (var NavChild = NavFrame.firstChild; NavChild != null; NavChild = NavChild.nextSibling) {
      if (hasClass(NavChild, 'NavContent'))
        NavChild.style.display = 'block';
    }
    NavToggle.firstChild.data = NavigationBarHide;
  }
}
 
// adds show/hide-button to navigation bars
function createNavigationBarToggleButton()
{
  var indexNavigationBar = 0;
  // iterate over all <div>-elements 
  var divs = document.getElementsByTagName("div");
  for (var i = 0; NavFrame = divs[i]; i++) {
    // if found a navigation bar
    if (!hasClass(NavFrame, "NavFrame")) continue;
    indexNavigationBar++;
    var NavToggle = document.createElement("a");
    NavToggle.className = 'NavToggle';
    NavToggle.setAttribute('id', 'NavToggle' + indexNavigationBar);
    NavToggle.setAttribute('href', 'javascript:toggleNavigationBar(' + indexNavigationBar + ');');
    var isCollapsed = hasClass(NavFrame, "collapsed");
    /*
     * Check if any children are already hidden.  This loop is here for backwards compatibility:
     * the old way of making NavFrames start out collapsed was to manually add style="display:none"
     * to all the NavPic/NavContent elements.  Since this was bad for accessibility (no way to make
     * the content visible without JavaScript support), the new recommended way is to add the class
     * "collapsed" to the NavFrame itself, just like with collapsible tables.
     */
    for (var NavChild = NavFrame.firstChild; NavChild != null && !isCollapsed; NavChild = NavChild.nextSibling) {
      if (hasClass(NavChild, 'NavPic') || hasClass(NavChild, 'NavContent')) {
        if (NavChild.style.display == 'none') 
          isCollapsed = true;
      }
    }
    if (isCollapsed) {
      for (var NavChild = NavFrame.firstChild; NavChild != null; NavChild = NavChild.nextSibling) {
        if (hasClass(NavChild, 'NavContent'))
          NavChild.style.display = 'none';
      }
    }
    var NavToggleText = document.createTextNode(isCollapsed ? NavigationBarShow : NavigationBarHide);
    NavToggle.appendChild(NavToggleText);
    // Find the NavHead and attach the toggle link (Must be this complicated because Moz's firstChild handling is borked)
    for(var j=0; j < NavFrame.childNodes.length; j++) {
      if (hasClass(NavFrame.childNodes[j], "NavHead"))
        NavFrame.childNodes[j].appendChild(NavToggle);
    }
    NavFrame.setAttribute('id', 'NavFrame' + indexNavigationBar);
  }
}

/** Fedora packages ********************************************************************* */

/* Document body */
body = function() { return document.body; }

/* Document head */
head = function() { return document.getElementsByTagName("head")[0] }

/* Prepend child */
prepch = function(elem, child) { 
    try {
	if (child instanceof Array) {
	    firstc = elem.firstChild
	    for (var c in child)
		elem.insertBefore(child[c], firstc);
	    return elem;
	}
	elem.insertBefore(child, elem.firstChild);
    } catch (e) {
	alert("Exception: " + e + 
	      "\n\nElem: " + elem +
	      "\n\nChild: " + child +
	      "\n\nStack trace: " + stacktrace());
    }
    return elem;
}

/* Append child */
appch = function(elem, child) { 
    try {
	if (child instanceof Array) {
	    for (var c in child)
	      elem.appendChild(child[c]);
	    return elem;
	}
	elem.appendChild(child);
    } catch (e) {
	alert("Exception: " + e + 
	      "\n\nElem: " + elem +
	      "\n\nChild: " + child +
	      "\n\nStack trace: " + stacktrace());
    }
    return elem;
}

/* Create element */
el = function(name) { return document.createElement(name); }
/* Create text */
t = function(text) { return document.createTextNode(text); }
/* Create list item */
li = function(child) { return appch(el("li"), child); }
/* Set attribute. Returns elem. */
attr = function(elem, key, value) { elem.setAttribute(key, value); return elem; }
/* Create link. */
a = function(href, child) { return appch(attr(el("a"), "href", href), child); }

/* Create title and document's H1. */
title = function(text) { 
    document.title = text;
    preponload(function() { prepch(body(), h1(t(text))); });
}

/* Create header. */
h1 = function(child) { return appch(el("h1"), child); }

/* Fedora package */
fedorapkg = function(name, homepage) {
    /* Red Hat Bugzilla Component Link */
    cl = function(component, product, productTitle) {
	return a("https://bugzilla.redhat.com/buglist.cgi?component=" + 
		 component + "&amp;product=" + product, t(productTitle + " Bugs")); }
    fedora = function(comp) { return cl(comp, "Fedora", "Fedora"); }
    rhel4 = function(comp) { return cl(comp, "Red%20Hat%20Enterprise%20Linux%204", "RHEL4"); }
    rhel5 = function(comp) { return cl(comp, "Red%20Hat%20Enterprise%20Linux%205", "RHEL5"); }
    rhel6 = function(comp) { return cl(comp, "Red%20Hat%20Enterprise%20Linux%206", "RHEL6"); }
    pkgdb = function(comp) { return a("https://admin.fedoraproject.org/pkgdb/acls/name/" + name,
				      t("Fedora Package Database")); }
    return appch(el("ul"), [li(a(homepage, t("homepage"))), li(fedora(name)), li(rhel6(name)), 
			    li(rhel5(name)), li(rhel4(name)), li(pkgdb(name))]);
}

/* Returns stack trace. */
stacktrace = function() {
    try {
	i.dont.exist += 0;
    } catch(e) {
	return e.stack;
    }
}

/* Prepend function to the window.onload list. */
preponload = function(handler) {
    if (typeof window.onload == 'function') {
        var oldhandler = window.onload;
        window.onload = function() { 
	    handler(); 
	    if (oldhandler) 
		oldhandler(); 
	};
    } else 
        window.onload = handler;
};

/* Append function to the window.onload list. */
apponload = function(handler) {
    if (typeof window.onload == 'function') {
        var oldhandler = window.onload;
        window.onload = function() { 
	    if (oldhandler) 
		oldhandler(); 
	    handler(); 
	};
    } else 
        window.onload = handler;
};

/** VARIA ********************************************************************* */

rootpath = function() {
    var scripts = document.getElementsByTagName('script');
    for (var i = 0; i < scripts.length; i++) {
      if (scripts[i].src.match(/main\.js(\?.+)?$/)) {
        return scripts[i].src.replace(/main\.js(\?.+)?$/, '');
      }
    }
    return "";
}

/* Include a script. */
incscript = function(fileName) {
    prepch(head(), attr(attr(el("script"), 
			     "type", "text/javascript"), 
			"src", fileName));
}

/* Include a stylesheet. */
inccss = function(fileName, media) {
    appch(head(), attr(attr(attr(attr(el("link"), 
				      "rel", "stylesheet"),
				 "type", "text/css"),
			    "media", media),
		       "href", fileName))
}

inccss(rootpath() + "site.css", "screen, projection");
var shjspath = "file:///usr/share/shjs/";
inccss(shjspath + "css/sh_acid.min.css", "screen, projection");
incscript(shjspath + "sh_main.min.js");

["c", "cpp", "csharp", "css", "html", "java", "javascript", 
 "latex", "makefile", "pascal", "perl", "php", "prolog", "python",
 "ruby", "sh", "sql", "tcl", "xml"].forEach(function(item) {
	 incscript(shjspath + "lang/sh_" + item + ".min.js");
     });
// missing: Windows Registry (sh_winreg), Lua, Lisp, Scheme, Groovy, 
// ELisp (emacs lisp), NSIS2

apponload(function() { 
  try { 
    sh_highlightDocument()
  } catch (err) {}

  try {
    createNavigationBarToggleButton()
  } catch (err) {
    //alert(err);
  }
  
  // Decorate outgoing links.
  var links = document.getElementsByTagName('a');
  for (var i = 0; i < links.length; i++) {
    link = links[i]
    if (link.href.match(/^(https?|ftps?):\/\//)) {
      // Ignore empty links.
      if (!link.hasChildNodes()) continue;
      // Ignore image links.
      if (link.firstChild.nodeType != 3) continue; // 3=TEXT_NODE
      // Decorate.
      link.firstChild.appendData("↗")
    }
  }
})