// main.js - script for kinderarzt dr. herzel - © lucdesign 2011

// one global variable
var articles =
{
  sidemenu: false,
  bottom: 0,
  top: 0
};

addEvent(window, 'load', init);
addEvent(window, 'scroll', scrollMenu);
addEvent(window, 'resize', scrollMenu);


// utility function
function addEvent (d, e, h) { try { d.attachEvent('on' + e, h); } catch(x) { d.addEventListener(e, h, false); } }

// init will be called by the body.onload event
function init ()
{
  try
  {
    wrapInSpans(document.getElementById('kopfzeile1').firstChild);
    shuffleColors(document.getElementById('kopfzeile1').firstChild);
    var contents = document.getElementById('contents');
    addOnclickHandler(contents);
    articles = contents.getElementsByTagName('article');
    articles.top = yPos(articles[0]);
    handleCollapsibleArticles();
    handlePrintableArticles();
    articles.sidemenu = document.getElementById('sidemenu');
    if (!window.location.pathname.match(/.*index\.php/))
    {
      addEvent(document.getElementById('kopfzeile1'), 'click', function(){window.location = 'index.php';});
    }
  }
  catch(e) {}
  addClass(contents, 'ready');
}

// this will be called from scrollMenu to determine the current document height
function lowestArticleBottom ()
{
  var lowestBottom = 0, thisBottom = 0;
  for (var i = 0; i < articles.length; i++)
  {
    thisBottom = yPos(articles[i]) + articles[i].offsetHeight;
    if (articles[i] != articles.sidemenu && thisBottom > lowestBottom) lowestBottom = thisBottom;
  }
  return lowestBottom;
}

// onclick function to manage "hashed" links to anchors on the same page: 
// expand the target article and add it's id as hash to the URL
function addOnclickHandler (contentArea)
{
  try
  {
    var contentLinks = contentArea.getElementsByTagName('a');
    for (var i = 0, ctl = contentLinks.length; i < ctl; i++)
    { 
      addEvent(contentLinks[i], 'click', function()
      { 
        if (this.href.split('#')[0] === document.URL.split('#')[0]) // if we stay on the same page
        {
          try
          {
            var theHash = this.href.split('#')[1]; // extract the hash from the link (should be all there is)
            window.location.hash = theHash; // add it to the URL
            showArticle(document.getElementById(theHash), 'yes'); // expand the article
          }
          catch(e) {}
        }
      });
    }
  }
  catch(e) {}
}

// add arrow, make title bar clickable for collapsible articles. this function is called once after page load
function handleCollapsibleArticles ()
{
  var hash = document.URL.split('#')[1];
  for (var i = 0; i < articles.length; i++)
  {
    if (hasClass(articles[i], 'collapsible'))
    {
      var articleHeader = articles[i].getElementsByTagName('h2')[0];
      articleHeader.style.cursor = 'pointer';
      // for IE7 we check if 'event' exists ... then we must use event.srcElement
      addEvent(articleHeader, 'click', function(e) { try { showArticle(event.srcElement.parentNode, 'toggle'); } catch(x) { showArticle(e.target.parentNode, 'toggle');} });
      var arrow = document.createElement('div');
      arrow.className = 'boxarrow';
      articleHeader.appendChild(arrow);
      addEvent(arrow, 'click', function(e) { try { showArticle(event.srcElement.parentNode.parentNode, 'toggle'); } catch(x) { showArticle(e.target.parentNode.parentNode, 'toggle');} });
      arrow.style.top = '0px'; var redrawFix = arrow.offsetHeight; // redraw fix for --- drum roll --- IE7
      if (articles[i].id != hash) showArticle(articles[i], 'no');
    }
  }
}

// add a new functional print button
function handlePrintableArticles ()
{
  for (var i = 0; i < articles.length; i++)
  {
    if (hasClass(articles[i], 'printable'))
    {
      // for IE7 we check if 'event' exists ... then we must use event.srcElement
      var printButton = document.createElement('div');
      printButton.className = 'printButton';
      articles[i].lastChild.appendChild(printButton);
      addEvent(printButton, 'click', function(e) {
        
        if (e)  try {
          printArticle(event.srcElement.parentNode.parentNode);
        } catch(x) {
          printArticle(e.target.parentNode.parentNode);
        }
      });
      printButton.style.bottom = '2px'; var redrawFix = printButton.offsetHeight; // redraw fix for --- drum roll --- IE7
    }
  }
}

// handle showing and hiding articles (via classname 'collapsed')
function showArticle (theArticle, showit)
{
  shuffleColors(document.getElementById('kopfzeile1').firstChild);
  switch (showit)
  {
    case 'yes': zapClass(theArticle, 'collapsed'); break;
    case 'no': addClass(theArticle, 'collapsed'); break;
    case 'toggle':
     if (hasClass(theArticle, 'collapsed'))
    {
      zapClass(theArticle, 'collapsed');
      // window.location.hash = theArticle.id;
    }
    else
    {
      addClass(theArticle, 'collapsed');
      window.location.hash = '';
    }
    break;
  }
  articles.bottom = lowestArticleBottom();
  scrollMenu();
}

// sroll sidemenu when applicable (via margin-top)
function scrollMenu ()
{
  if (articles.sidemenu) // exists
  {
    var scrollRange = articles.bottom - articles.top - articles.sidemenu.offsetHeight, menuScroll = 0;
    if (scrollRange > 0)
    {
      var scrollPos = yScroll() - articles.top + 20;
      if (scrollPos > 0) menuScroll = Math.min(scrollPos, scrollRange);
    }
    articles.sidemenu.style.marginTop = menuScroll + 'px';
  }
}

// helper functions to find position ...
function yPos (obj)
{
  var curtop = 0;
  if (obj.offsetParent)
  {
    do curtop += obj.offsetTop; while (obj = obj.offsetParent);
    return curtop;
  }
}

// ... and scroll position
function yScroll ()
{
  if ( typeof( window.pageYOffset ) === 'number' )                      return window.pageYOffset; //Netscape compliant
  if ( document.body && document.body.scrollTop )                       return document.body.scrollTop; //DOM compliant
  if ( document.documentElement && document.documentElement.scrollTop ) return document.documentElement.scrollTop; //IE6 standards compliant mode
  return 0; // if nothing fits
}

function wrapInSpans (textNode) {
  textNode.innerHTML = '<span>' + textNode.innerHTML.split('').join('</span><span>') + '</span>';
}

function shuffleColors (spanContainer)
{
  var spans = spanContainer.childNodes, spanCount = spans.length, funnyByte, funnyColor;
  for ( var i=0; i < spanCount; i++ )
  {
    if (spans[i].nodeName.match(/^span$/i))
    {
      funnyColor = '#';
      for (var c = 0; c <3; c++)
      {
        funnyByte = (Math.floor((1 - Math.pow(Math.random(), 3)) * 255)).toString(16);
        while (funnyByte.length < 2) funnyByte = '0' + funnyByte;
        funnyColor += funnyByte;
      }
      spans[i].style.color = funnyColor;
    }
  }
}

// more helper functions for handling class names (no jquery here)
function clnClass (   c) { return c.replace(/\s{2,}/g, ' ').replace(/^\s/, '').replace(/\s$/, ''); }
function hasClass (e, c) {
  try {
    if (e.className) {
      var exp = new RegExp('(\\s|^)'+c+'(\\s|$)');
      return exp.test(e.className);
    }
  }
  catch(x){}
  return false;
}
function zapClass (e, c) { if (hasClass(e, c)) e.className = clnClass(e.className.replace(new RegExp('(\\s|^)'+c+'(\\s|$)'),'')); }
function addClass (e, c) {
  try
  {
    if (!hasClass(e, c)) e.className = clnClass(e.className + ' ' + c); 
  }
  catch(x)
  {
    e.className = clnClass(c);
  }
}

function printArticle (theArticle)
{
  var allArticles = document.getElementsByTagName('article');
  for (var i = 0; i < articles.length; i++ ) {
    if (allArticles[i] === theArticle) {
      addClass(allArticles[i], 'printing');
    } else {
      zapClass(allArticles[i], 'printing');
    }
  }
  window.print();
}
