
//
// handle content section jumping etc.
//

//
// Requires:
//  createElement()         from utils.js
//  localOffsetTop()        from utils.js
//  createCustomScrollBar() from scroll.js
//

// alert('sections.js');



/*
 * Debug window
 */

debugdiv = undefined;
debug_enabled = false;

function init_debug() {
  if (debug_enabled) {
    debugdiv = createElement('div', {
	'style.backgroundColor': 'blue'    ,
	'style.position'       : 'absolute',
	'style.top'            : '0px'     ,
        'style.left'           : '400px'    });
    debugdiv.appendChild(debugtext = createElement('pre'));
    document.body.appendChild(debugdiv); }
  debug = function(s) {
    if (debug_enabled) debugtext.innerHTML += s + '<br>\n'; };
}


function copy_children(source, target, replacements) {
  // copy all children of element `source` 
  //       as children of element `target`, 
  // and do text substitutions listed in `replacements` for all text
  // nodes (e.g. [['accordion','acc'],[' and ','&']])
  for (var el=source.firstChild; el; el=el.nextSibling) {
    var clone = el.cloneNode(true);
    if (replacements && clone.nodeType == 3 /* TEXT_NODE */ ) {
      for (var i=0; i<replacements.length; ++i) {
	var rep = replacements[i];
	clone.data = clone.data.replace(rep[0], rep[1]); } }
    target.appendChild(clone); }
}


function create_section_a_tag(title, func) {
  // Create <a href="#" onclick="func('title');">
  // Headings will be wrapped with these in the index of the page.
  return createElement('a', {
      'className': 'indexentry',
      'href'     : '#',
      'onclick'  : new Function(func+'("'+dojo.string.escape('js', title)+'");') });
}

function create_section_toggle(title) {
  // Create <a href="#" onclick="showOnlySection('title');">
  // <H1> headings will be wrapped with these in the index of the page.
  return create_section_a_tag(title, 'showOnlySection');
}

function create_section_link(title) {
  // Create <a href="#" onclick="gotoSection('title');">
  // <H[23]> headings will be wrapped with these in the index of the page.
  return create_section_a_tag(title, 'gotoSection');
}


function adjust_story_height() {
  // Adjust <div id="story"> height so that it fits into <div
  // id="content">.
    
  var story   = dojo.byId('story');
  var content = dojo.byId('content');
  var textOffsetTop = localOffsetTop(story);
  // story.style.height = content.offsetHeight - textOffsetTop + 'px';
  // // content.offsetHeight is not updated in IE6
  story.style.height = parseInt(content.style.height) - textOffsetTop + 'px';

  // if (story.scrollHeight > story.clientHeight) {
  // Story is longer than window, show index and scroll bar.
  
  //debug('textOffsetTop='+textOffsetTop);
  textOffsetTop = localOffsetTop(story);

  //debug('content.offsetHeight='+content.offsetHeight);
  //debug('content.style.height='+content.style.height);
  //debug('localOffsetTop(story)='+textOffsetTop);
  createCustomScrollBar(content, story);
}


function adjust_bottom_padding(story, lastheading, lasttag) {
  // If the last section (from last H2 to end) doesn't fill a page,
  // add padding to the last element
  
  // alert('lasttag='+lasttag.innerHTML+', lastheading='+lastheading.innerHTML);
  if (lastheading) {
    lasttag.style.paddingBottom = 0;
    var last_section_height = 
      lasttag.offsetTop 
      + lasttag.offsetHeight 
      - lastheading.offsetTop;
    if (last_section_height < story.clientHeight)
      lasttag.style.paddingBottom = story.clientHeight - last_section_height;
  }
}


/*
 * Main content initialization
 *
 * If length of content exceeds screen height, create separate index
 * and story elements for navigation and scrolling.
 */

function init_sections() {

  init_debug();

  // alert('init_sections()');

  // find <div id="content">, which contains the raw story
  var content = dojo.byId('content');
  if (content && content.className.indexOf('images') < 0)
    init_sections2(content);
  content.style.visibility = 'visible';
}

function init_sections2(content) {
  var windowheight;
  if (!(windowheight = window.innerHeight))           /* firefox */
    windowheight = document.body.parentNode.scrollHeight; /* ie6 */
  debug('windowheight='+windowheight);
  var vertmargins = 2 * globalOffsetTop(content);
  debug('vertmargins='+vertmargins);
  document.body.style.height = windowheight + "px";
  content.style.height = (windowheight - vertmargins) + "px"; 

  // Create the <div id="index">, which will contain links for jumping
  // to each <h2> in the story
  var index = createElement('div', {'id': 'index'});

  // Create the <div id="story" class="scrollable">, into which the
  // story elements will be moved from <div id="content">.
  var story  = createElement('div', {
      'id'       : 'story', 
      'className': 'scrollable'});

  // Iterate through story elements.  Copy <h[23]>'s into <div
  // id="index"> and add JavaScript links to them.  Move all elements
  // from <div id="content"> to <div id="story">.

  var 
    tag,       // iterates through all elements
    h3s = false,
    lastH2,    // store the last <H2> tag    
    lastH,     // store the last <H2> or <H3> tag \ for padding last section
    lasttag,   // store the last of all tags      / if shorter than scroll window
    h1count=0, // store the number of <H1> tags
    hcount=0;  // counter for H? tags: USE THIS FOR UNIQUE TITLES
               // WHEN TEXT OF TITLE IS IDENTICAL
               // En saanut vielä toimimaan, ks. "find it later when scrolling"

  while (tag=content.firstChild) {

    // Move story elements from <div id="content"> into 
    // <div id="story">.
    content.removeChild(tag);

    if (tag.nodeType == 1 /* ELEMENT_NODE */ ) {
      lasttag = tag;

      if (tag.tagName.match(/H\d/)) {
	lastH = tag;
	// Use the title in <h2>title</h2> as id for the tag so we can
	// find it later when scrolling.
	var title = tag.firstChild.data; // hcount + '_' + ... ei toiminut
	tag.id    = title;
	//debug(title);


	if (tag.tagName == 'H1') {
	  var a = create_section_toggle(title);
	  var h1 = createElement('h1', {});
	  copy_children(tag, h1);
	  a.appendChild(h1);
	  index.appendChild(a);
	  h1count++;


	} else if (tag.tagName == 'H2') {
	  lastH2 = tag;
      
	  // Copy <h2> children into the newly created <a>.
	  // TODO: vain konsertteihin:
	  var a = create_section_link(title);
	  a.appendChild(createElement('img', {
			    'src': 'img/rightarrow2.png',
			    'style.marginRight': '3px'}));
	  copy_children(tag, a);

	  if (h3s) {
	    // insert preceding subheading links first
	    index.appendChild(h3s);
	    //debug(h3s.innerHTML);
	    h3s = false; }

	  index.appendChild(a); 


	} else if (tag.tagName == 'H3') {

	  if (!h3s) h3s = createElement('p', {'className': 'indexsubentries'});
	  // Copy <h3> children into the newly created <a>.
	  // TODO: vain konsertteihin:
	  var a = create_section_link(title);
	  a.appendChild(createElement('img', 
				      {'src'              : 'img/rightarrow2.png', 
				       'style.marginRight': '3px'}));
	  copy_children(tag, a, [['accordion','acc'], [' and ','&']]);
	  h3s.appendChild(a);
	  h3s.appendChild(document.createTextNode(' '));
	}  

      }
    } 
    if (tag) story.appendChild(tag);
  }
  if (h3s) {
    index.appendChild(h3s);
    //debug(escape(h3s.innerHTML));
  }

  // story.firstChild.style.marginTop = '0px';

  for (var el=story.firstChild; el; el=el.nextSibling)
    // Adjust the top margin of the first story element
    if (el.nodeType == 1)  {
      el.style.marginTop = '2px';
      break;
    }

  // Insert the generated index and story parts into <div id="content">.
  content.appendChild(index);
  content.appendChild(story);

  if (h1count > 1) showOnlySection(null);

  adjust_story_height();
  adjust_bottom_padding(story, lastH, lasttag);

  // alert('init_sections() done');
  
}

function gotoSection(sectionname) {
  scrollTo(dojo.byId('story'), localOffsetTop(dojo.byId(sectionname)));
}

function showOnlySection(sectionname) {
  // UNDER CONSTRUCTION
  var index = dojo.byId('index');
  var story = dojo.byId('story');
  var visibility = 'none';
  var lasttag, lastheading;
  for (var el=index.firstChild; el; el=el.nextSibling) {
    if (el.nodeType == 1) {
      if (el.tagName == 'A' && el.firstChild.tagName == 'H1') {
	visibility = el.firstChild.firstChild.data == sectionname;
	el.className = visibility ? 'intexentry' : 'indexentry folded';
      }
      else el.className = visibility ? 'indexentry' : 'indexentry hidden';
    }
  }
  for (var el=story.firstChild; el; el=el.nextSibling) {
    if (el.nodeType == 1) {
      if (el.tagName.match(/H\d/)) {
	if (el.tagName == 'H1')
	  visibility = el.id == sectionname ? '' : 'hidden';
	if (visibility == '') lastheading = el;
      }
      el.className = visibility;
      if (visibility == '') lasttag = el;
    }
  }
  adjust_story_height();
  if (lasttag) adjust_bottom_padding(story, lastheading, lasttag);
}



// alert('sections.js done');
