/**
 * hoverIntent is similar to jQuery's built-in "hover" function except that
 * instead of firing the onMouseOver event immediately, hoverIntent checks to
 * see if the user's mouse has slowed down (beneath the sensitivity threshold)
 * before firing the onMouseOver event.
 * 
 * hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
 * <http://cherne.net/brian/resources/jquery.hoverIntent.html>
 * 
 * hoverIntent is currently available for use in all personal or commercial
 * projects under both MIT and GPL licenses. This means that you can choose the
 * license that best suits your project, and use it accordingly.
 *  // basic usage (just like .hover) receives onMouseOver and onMouseOut
 * functions $("ul li").hoverIntent( showNav , hideNav );
 *  // advanced usage receives configuration object only $("ul
 * li").hoverIntent({ sensitivity: 7, // number = sensitivity threshold (must be
 * 1 or higher) interval: 100, // number = milliseconds of polling interval
 * over: showNav, // function = onMouseOver callback (required) timeout: 0, //
 * number = milliseconds delay before onMouseOut function call out: hideNav //
 * function = onMouseOut callback (required) });
 * 
 * @param f
 *            onMouseOver function || An object with configuration options
 * @param g
 *            onMouseOut function || Nothing (use configuration options object)
 * @author Brian Cherne <brian@cherne.net>
 */
(function($) {
	$.fn.hoverIntent = function(f,g) {
		// default configuration options
		var cfg = {
			sensitivity: 7,
			interval: 20,
			timeout: 0
		};
		// override configuration options with user supplied object
		cfg = $.extend(cfg, g ? { over: f, out: g } : f );

		// instantiate variables
		// cX, cY = current X and Y position of mouse, updated by mousemove
		// event
		// pX, pY = previous X and Y position of mouse, set by mouseover and
		// polling interval
		var cX, cY, pX, pY;

		// A private function for getting mouse position
		var track = function(ev) {
			cX = ev.pageX;
			cY = ev.pageY;
		};

		// A private function for comparing current and previous mouse position
		var compare = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			// compare mouse positions to see if they've crossed the threshold
			if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
				$(ob).unbind("mousemove",track);
				// set hoverIntent state to true (so mouseOut can be called)
				ob.hoverIntent_s = 1;
				return cfg.over.apply(ob,[ev]);
			} else {
				// set previous coordinates for next time
				pX = cX; pY = cY;
				// use self-calling timeout, guarantees intervals are spaced out
				// properly (avoids JavaScript timer bugs)
				ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
			}
		};

		// A private function for delaying the mouseOut function
		var delay = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			ob.hoverIntent_s = 0;
			return cfg.out.apply(ob,[ev]);
		};

		// A private function for handling mouse 'hovering'
		var handleHover = function(e) {
			// next three lines copied from jQuery.hover, ignore children
			// onMouseOver/onMouseOut
			var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
			while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
			if ( p == this ) { return false; }

			// copy objects to be passed into t (required for event object to be
			// passed in IE)
			var ev = jQuery.extend({},e);
			var ob = this;

			// cancel hoverIntent timer if it exists
			if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

			// else e.type == "onmouseover"
			if (e.type == "mouseover") {
				// set "previous" X and Y position based on initial entry point
				pX = ev.pageX; pY = ev.pageY;
				// update "current" X and Y position based on mousemove
				$(ob).bind("mousemove",track);
				// start polling interval (self-calling timeout) to compare
				// mouse coordinates over time
				if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

			// else e.type == "onmouseout"
			} else {
				// unbind expensive mousemove event
				$(ob).unbind("mousemove",track);
				// if hoverIntent state is true, then call the mouseOut function
				// after the specified delay
				if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
			}
		};

		// bind the function to the two event listeners
		return this.mouseover(handleHover).mouseout(handleHover);
	};
})(jQuery);

function ndeSetStyleSheet(newtitle) 
{
  ndeCreateCookie('nde-style', newtitle, 365, false);
  if (ndeReadCookie('nde-style') == newtitle)
  {
    window.location.reload(true);
  }
  else
  {
    alert('You must enable Cookies in order for theme selection to work');
  }
}

function ndeSetTextSize(chgsize,rs) 
{
  if (!document.documentElement || !document.body)
  {
    return;
  }

  var newSize;
  var startSize = parseInt(ndeGetDocTextSize());

  if (!startSize)
  {
    startSize = 12;
  }

  switch (chgsize)
  {
  case 'incr':
    newSize = startSize + 2;
    break;

  case 'decr':
    newSize = startSize - 2;
    break;

  case 'reset':
    if (rs) 
    {
      newSize = rs;
    } 
    else 
    {
      newSize = 12;
    }
    break;

  default:
    newSize = parseInt(ndeReadCookie('nde-textsize', true));
    if (!newSize)
    {
      newSize = startSize;
    }
    break;

  }

  if (newSize < 10) 
  {
    newSize = 10;
  }

  newSize += 'px';

  document.documentElement.style.fontSize = newSize;
  document.body.style.fontSize = newSize;

  ndeCreateCookie('nde-textsize', newSize, 365, true);
}

function ndeGetDocTextSize() 
{
  if (!document.body)
  {
    return 0;
  }

  var size = 0;
  var body = document.body;

  if (body.style && body.style.fontSize)
  {
    size = body.style.fontSize;
  }
  else if (typeof(getComputedStyle) != 'undefined')
  {
    size = getComputedStyle(body,'').getPropertyValue('font-size');
  }
  else if (body.currentStyle)
  {
    size = body.currentStyle.fontSize;
  }
  return size;
}

function ndeCreateCookie(name,value,days,useLang) 
{
  var langString = useLang ? ndeGetLang() : '';

  var cookie = name + langString + '=' + value + ';';

  if (days) 
  {
    var date = new Date();
    var ndeMilliSecondsInDay = 86400000; // 24*60*60*1000
    date.setTime(date.getTime()+(days*ndeMilliSecondsInDay));
    cookie += ' expires=' + date.toGMTString() + ';';
  }
  cookie += ' path=/';

  document.cookie = cookie;
}

function ndeReadCookie(name, useLang) 
{
  var langString = useLang ? ndeGetLang() : '';

  var nameEQ = name + langString + '=';
  var ca = document.cookie.split(';');

  for(var i = 0; i < ca.length; i++) 
  {
    var c = ca[i];
    while (c.charAt(0) == ' ') 
    {
      c = c.substring(1, c.length);
    }

    if (c.indexOf(nameEQ) == 0) 
    {
      return c.substring(nameEQ.length,c.length);
    }
  }
  return null;
}

function ndeSetTheme()
{
  ndeSetTextSize();
  return true;
}

function ndeGetLang()
{
  var langString = '';

  if (document.documentElement){
    langString = document.documentElement.lang;
    if (langString != ''){
      langString = '-' + langString;
    }
  }  
  return langString;
}


function printAlert() 
{
  alert('Thanks to the use of a print-media stylesheet, this page is already printer-friendly!  Just print the article from a CSS-capable browser to get the print styles on paper.');
}


// ///////////////////////////

function menuinit() 
{
  cssjsmenu('navbar');
  if (document.getElementById)
  {
    var kill = document.getElementById('hoverJS'); 
    if (kill)
    	kill.disabled = true;
  }
  
  if (typeof(onLoad2)=="function")
  	onLoad2();
}

// csjsmenu.js

function elementContains(elmOuter, elmInner)
{
  while (elmInner && elmInner != elmOuter)
  {
    elmInner = elmInner.parentNode;
  }
  if (elmInner == elmOuter)
  {
    return true;
  }
  return false;
}

function getPageXY(elm)
{
  var point = { x: 0, y: 0 };
  while (elm)
  {
    point.x += elm.offsetLeft;
    point.y += elm.offsetTop;
    elm = elm.offsetParent;
  }
  return point;
}

function setPageXY(elm, x, y)
{
  var parentXY = {x: 0, y: 0 };

  if (elm.offsetParent)
  {
    parentXY = getPageXY(elm.offsetParent);
  }

  elm.style.left = (x - parentXY.x) + 'px';
  elm.style.top  = (y - parentXY.y) + 'px';
}

/* ------------------------------------------------------------ */
/* file boundary */

function cssjsmenu(menuid)
{
  var i;
  var j;
  var node;
  var child;
  var parent;

  // if the browser doesn't even support
  // document.getElementById, give up now.
  if (!document.getElementById)
  {
    return true;
  }

  // check for downlevel browsers
  // Opera 6, IE 5/Mac are not supported

  var version;
  var offset;

  offset = navigator.userAgent.indexOf('Opera');
  if (offset != -1)
  {
    version = parseInt('0' + navigator.userAgent.substr(offset + 6), 10);
    if (version < 7)
    {
      return true;
    }
  }

  offset = navigator.userAgent.indexOf('MSIE');
  if (offset != -1)
  {
    if (navigator.userAgent.indexOf('Mac') != -1)
    {
      return true;
    }
  }

  var menudiv = document.getElementById(menuid);

  // ul
  var ul = new Array();

if (menudiv && menudiv.childNodes) {
  for (i = 0; i < menudiv.childNodes.length; i++)
  {
    node = menudiv.childNodes[i];
    if (node.nodeName.toUpperCase() == 'UL')
    {
      ul[ul.length] = node;
    }
  }
 }
  

  // ul > li
  var ul_gt_li = new Array();

  for (i = 0; i < ul.length; i++)
  {
    node = ul[i];
    for (j = 0; j < node.childNodes.length; j++)
    {
      child = node.childNodes[j];
      if (child.nodeName.toUpperCase() == 'LI')
      {
        ul_gt_li[ul_gt_li.length] = child;
        child.style.display = 'inline';
        child.style.listStyle = 'none';
        child.style.position = 'static';
      }
    }
  }

  // ul > li > ul
  var ul_gt_li_gt_ul = new Array();

  for (i = 0; i < ul_gt_li.length; i++)
  {
    node = ul_gt_li[i];
    for (j = 0; j < node.childNodes.length; j++)
    {
      child = node.childNodes[j];
      if (child.nodeName.toUpperCase() == 'UL')
      {

        ul_gt_li_gt_ul[ul_gt_li_gt_ul.length] = child;
        child.style.position = 'absolute';
        child.style.left = '-13em';
        child.style.visibility = 'hidden';

        // attach hover to parent li
        parent = child.parentNode;
        parent.onmouseover = function (e)
        {
          var i;
          var child;
          var point;
          // stop the pure css hover effect
          this.style.paddingBottom = '0';

          for (i = 0; i < this.childNodes.length; i++)
          {
            child = this.childNodes[i];
            if (child.nodeName.toUpperCase() == 'UL')
            {
              point = getPageXY(this);
              setPageXY(child, point.x, point.y + this.offsetHeight);
              child.style.visibility = 'visible';
            }
          }
          return false;
        };

        parent.onmouseout = function (e)
        {
          var relatedTarget = null;
          if (e)
          {
            relatedTarget = e.relatedTarget;
            // work around Gecko Linux only bug where related target is null
            // when clicking on menu links or when right clicking and moving
            // into a context menu.
	    if (navigator.product == 'Gecko' && navigator.platform.indexOf('Linux') != -1 && !relatedTarget)
	    {
	      relatedTarget = e.originalTarget;
	    }
          }
          else if (window.event)
          {
            relatedTarget = window.event.toElement;
          }

          if (elementContains(this, relatedTarget))
          {
            return false;
          }

          var i;
          var child;
          for (i = 0; i < this.childNodes.length; i++)
          {
            child = this.childNodes[i];
            if (child.nodeName.toUpperCase() == 'UL')
            {
                child.style.visibility = 'hidden';
            }
          }
          return false;
        };
      }
    }
  }
  return true;
}


// onLoad2 can be used as additional onLoad-event-handler; called by init() if
// set
var onLoad2;

function toggleTOCVisibility() {
	element = document.getElementById("toclist");
	if (element) {
		alert();
		element.style.visibility = false;
		return  0;
		element.style.display = !element.style.visibility;
	}
}

function toggleToc() {
	var toc = document.getElementById('tocUL');
	var showlink = document.getElementById('showTOCLink');
	var hidelink = document.getElementById('hideTOCLink');
	if(toc.style.display == 'none') {
		toc.style.display = tocWas;
		hidelink.style.display='';
		showlink.style.display='none';

	} else {
		tocWas = toc.style.display;
		toc.style.display = 'none';
		hidelink.style.display='none';
		showlink.style.display='';

	}
}

function toggleSpanVisibility(id) {
	var el = document.getElementById(id);
	if(el.style.display == 'none') {
		el.style.display = 'inline';
	} else {
		el.style.display = 'none';
	}
}

function showToggleTOCSwitch(showTitle, hideTitle) {
	if(document.getElementById) {
		document.writeln('<span class=\'toctoggle\'>[<a href="javascript:toggleToc()" class="internal">' +
		'<span id="showTOCLink" style="display:none;">' + showTitle + '</span>' +
		'<span id="hideTOCLink">' + hideTitle + '</span>'
		+ '</a>]</span>');
	}
}


function printSpan(reference, title, body) {
  document.write("<span class=\"stretchtext\" style=\"display: none;\" id=\"" + reference + "\"> [<span class=\"title\">" + title + "</span> | <span class=\"body\">" +  body + "</span>]</span> ");       
}

function printDiv(reference, title, body) {
  document.write(" <span class=\"popup\" style=\"display: none;\" id=\"" + reference + "\"><div class=\"title\">" + title + "</div><div class=\"body\">" +  body + "</div></span>");       
}

      
function toggleDisplay (id) {

  if (document.getElementById) {
    var mydiv = document.getElementById(id);
    if (mydiv.tagName == "SPAN") { 
      mydiv.style.display = (mydiv.style.display=='block'?'none':'block');
    } else {
      mydiv.style.display = (mydiv.style.display=='block'?'none':'block');
    }    
  }
  return false;
}

// Object:
function xGetElementById(e) {
  if(typeof(e)!='string') return e;
  if(document.getElementById) e=document.getElementById(e);
  else if(document.all) e=document.all[e];
  else e=null;
  return e;
}

function hideMe(){
	var leftColumnOpen = xGetElementById('leftColumnOpen');
	leftColumnOpen.style.display = "none";
	var leftColumnClose = xGetElementById('leftColumnClose');
	leftColumnClose.style.width = "80%";
	leftColumnClose.style.left = "0px";
	var col2 = xGetElementById('col2');	
	col2.className = "close";
	col2.style.backgroundPosition = "0 0";
}

function showMe(){
	var leftColumnOpen = xGetElementById('leftColumnOpen');
	leftColumnOpen.style.display = "block";
	var leftColumnClose = xGetElementById('leftColumnClose');
	leftColumnClose.style.width = "60%";
	leftColumnClose.style.left = "20%";
	var col2 = xGetElementById('col2');	
	// col2.style.background = "url(/images/layout/tab.gif) repeat-y";
	col2.className = "open";
	col2.style.backgroundPosition = "0 0";
}

function getElementsByClass(node,searchClass,tag) {
	var classElements = new Array();
	var els = node.getElementsByTagName(tag); // use "*" for all elements
	var elsLen = els.length;
	var pattern = new RegExp("\\b"+searchClass+"\\b");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

var formSectionIds = new Array(); 

function showFormSection(id) {

	for (i = 0; i < formSectionIds.length; i++) {
			
		var element = document.getElementById(formSectionIds[i]); 
		var tocEntryElement = document.getElementById("tocEntry-" + formSectionIds[i]); 
		
		if (formSectionIds[i] == id) {
			
			element.setAttribute("class", "formSection"); 
			element.setAttribute("className", "formSection"); 
			
			tocEntryElement.setAttribute("class", "formTocEntryElement activeFormTocEntryElement"); 
			tocEntryElement.setAttribute("className", "formTocEntryElement activeFormTocEntryElement"); 
			
			
		} else {
			element.setAttribute("class", "formSection noDisplay"); 
			element.setAttribute("className", "formSection noDisplay"); 

			tocEntryElement.setAttribute("class", "formTocEntryElement inactiveFormTocEntryElement"); 
			tocEntryElement.setAttribute("className", "formTocEntryElement inactiveFormTocEntryElement"); 

		}
	
	}
	positionFooter(); 
}

function createFormTabs(viewletId) {


	var sectionElements = $("#" + viewletId + " .formSection");
	
	formTocNode = document.createElement("ul");
	
	var classAttribute = document.createAttribute("class");
	classAttribute.nodeValue = "formToc";
	
	formTocNode.setAttributeNode(classAttribute);
	
	for (i = 0; i < sectionElements.length; i++) {
		
		formSectionTitleDiv = sectionElements[i].firstChild;
		formSectionTitleDiv.setAttribute("class", "noDisplay"); 
		formSectionTitleDiv.setAttribute("className", "noDisplay"); 
		
		var idNode = sectionElements[i].getAttributeNode("id"); 
		formSectionId = idNode.nodeValue;
		formSectionIds[formSectionIds.length] = formSectionId;
		
		formTocEntryNode = document.createElement("li");
		formTocEntryNode.setAttribute("id", "tocEntry-" + formSectionId); 
		formTocEntryNode.setAttribute("class", "formTocEntryElement inactiveFormTocEntryElement"); 
		formTocEntryNode.setAttribute("className", "formTocEntryElement inactiveFormTocEntryElement"); 
		
		var formTocEntryAnchorNode = document.createElement("a");
		formTocEntryNode.appendChild(formTocEntryAnchorNode); 
		
		formTocEntryAnchorNode.setAttribute("href", "javascript: showFormSection('" + formSectionId + "');");	
		
		formTocEntryAnchorNode.innerHTML = formSectionTitleDiv.innerHTML; 
		formTocNode.appendChild(formTocEntryNode); 
	}
	

	var formHeaderElement = $("#" + viewletId + " .viewlet2Header");
	formHeaderElement.after(formTocNode); 

	showFormSection(formSectionIds[0]); 
}



function select_all(name, value) {


	formblock= document.getElementById('editForm');
	var forminputs = formblock.getElementsByTagName('input');

	for (i = 0; i < forminputs.length; i++) 
	{
		// regex here to check name attribute
		var regex = new RegExp(name, "i");
		if (regex.test(forminputs[i].getAttribute('name'))) 
		{
			if (value == '1') {
			
				forminputs[i].checked = true;
			} else {
				forminputs[i].checked = false;
			}
		}
	}
}


function select_allContentObjectProxyLIds(value) {

	var searchQuery = $("#contentObjectProxyQueryString").val(); 
	
	if (searchQuery == "") { 
		select_all("contentObjectProxyLIds", value);		
	} else {

		// regex here to check name attribute
		var regex = new RegExp(searchQuery, "i");	
	    tableTRs = $(".checkboxTableForExport tr").each(function() {     	

			if (regex.test($(".localName", this).html())) {
				if (value == '1') {
					$("input", this).attr('checked', true);
				} else {
					$("input", this).attr('checked', false);
				}
			
			}
	    });
	
		
	}
}


var insertFlash = true;

function insertFlashMedium(filename, width, height, alttext) {
  if (insertFlash == true) {
    document.writeln("<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0' height='" + height + "' width='" + width + "'>"); 
    document.writeln("<param name='movie' value='" + filename + "'/>");
    document.writeln("<param name='quality' value='high'/>"); 
    document.writeln("<embed height='" + height + "' pluginspage='http://www.macromedia.com/go/getflashplayer' quality='high' src='" + filename + "' type='application/x-shockwave-flash' width='" + width + "'/>"); 
    document.writeln("<p class='flashDescription'>" + alttext + "</p>"); 
    document.writeln("</object>");
  } else {
    document.writeln("<p>" + alttext + "</p>"); 
  } 
}


$(function() {

$('.teaser').hover(function() {
  $(this).addClass('teaser-hover');
}, function() {
  $(this).removeClass('teaser-hover');
});


$('.teaser').click(function() {
	
	 $(this).removeClass('teaser-hover');
	var href = $("a.teaserLink", this).attr('href');
	location.href = href; 
	
});

$('.listGrid tr.hoverable').hover(function() {
  $(this).addClass('hover');
}, function() {
  $(this).removeClass('hover');
});

$('.listGrid tr').click(function() {
	
	var href = $("a.openLink", this).attr('href');
	if (href)
		location.href = href; 
	
});

	
 
});

/* HIGHLIGHTING */

/* http://www.kryogenix.org/code/browser/searchhi/ */
/* Modified 20021006 to fix query string parsing and add case insensitivity */

function highlightWord(node,word) {
	// Iterate into this nodes childNodes
	if (node.hasChildNodes) {
		var hi_cn;
		for (hi_cn=0;hi_cn<node.childNodes.length;hi_cn++) {
			highlightWord(node.childNodes[hi_cn],word);
		}
	}
	
	// And do this node itself
	if (node.nodeType == 3) { // text node
		tempNodeVal = node.nodeValue.toLowerCase();
		tempWordVal = word.toLowerCase();
		if (tempNodeVal.indexOf(tempWordVal) != -1) {
			pn = node.parentNode;
			if (pn.className != "searchword") {
				// word has not already been highlighted!
				nv = node.nodeValue;
				ni = tempNodeVal.indexOf(tempWordVal);
				// Create a load of replacement nodes
				before = document.createTextNode(nv.substr(0,ni));
				docWordVal = nv.substr(ni,word.length);
				after = document.createTextNode(nv.substr(ni+word.length));
				hiwordtext = document.createTextNode(docWordVal);
				hiword = document.createElement("span");
				hiword.className = "searchword";
				hiword.appendChild(hiwordtext);
				pn.insertBefore(before,node);
				pn.insertBefore(hiword,node);
				pn.insertBefore(after,node);
				pn.removeChild(node);
			}
		}
	}
}

function googleSearchHighlight() {
	if (!document.createElement) return;
	ref = document.referrer;
	if (ref.indexOf('?') == -1) return;
	qs = ref.substr(ref.indexOf('?')+1);
	qsa = qs.split('&');
	for (i=0;i<qsa.length;i++) {
		qsip = qsa[i].split('=');
	        if (qsip.length == 1) continue;
        	if (qsip[0] == 'q' || qsip[0] == 'p') { // q= for Google, p= for
													// Yahoo
			words = unescape(qsip[1].replace(/\+/g,' ')).split(/\s+/);
	                for (w=0;w<words.length;w++) {
				highlightWord(document.getElementsByTagName("body")[0],words[w]);
                	}
	        }
	}
}

function highlightWords(node, s)  {

	if (s != '')
	{	
		words = s.split(/\s+/);
		for (w=0;w<words.length;w++) {
			for (e = 0; e < document.getElementsByTagName("span").length; e++)
			{
				if (document.getElementsByTagName("span")[e].className == "searchable")
				{
					highlightWord(document.getElementsByTagName("span")[e], words[w]);
				}; 
			}
		}
	}
}


function positionFooter() {
	
	if ($("#content").height() < ($(window).height()-$("#pageFooter").height()-$("#pageHeader").height()-50)) {
		$("#pageFooter").css("position", "absolute").css("bottom", "0px").width($(document).width());
	} else {
		$("#pageFooter").css("position", "relative").css("bottom", "");
	}
	
}


jQuery(document).ready(function(){

	$(".foldingBoxOpen").each(function(index){									   
		$(".boxTitle", this).prepend("<img src='" + themePath + "foldingbox-open.png' width='25' height='20' class='foldboxIcon'/>"); 	
		$(this).addClass("foldingBox");
	});
	$(".foldingBoxClosed").each(function(index){									   
		$(".boxTitle", this).prepend("<img src='" + themePath + "foldingbox-closed.png' width='25' height='20' class='foldboxIcon'/>"); 
		$(".boxBody", this).hide();
		$(this).addClass("foldingBox");
	});

	$('.foldingBox .boxTitle').click(function(){ 
											  
													
		if ($(this).parent().is(".foldingBoxClosed")) {
			
			$(this).parent().addClass("foldingBoxOpen");								  
			$(this).parent().removeClass("foldingBoxClosed");								  
			$('.boxTitle img', $(this).parent()).attr("src", themePath + "foldingbox-open.png");	
	
		} else if ($(this).parent().is(".foldingBoxOpen")) {
			
			$(this).parent().addClass("foldingBoxClosed");								  
			$(this).parent().removeClass("foldingBoxOpen");								  
			$('.boxTitle img', $(this).parent()).attr("src", themePath + "foldingbox-closed.png");	
		}
	
		$(".boxBody", $(this).parent()).toggle();

	});



});

// Ajax Tooltip script: By JavaScript Kit: http://www.javascriptkit.com
// Last update (July 10th, 08'): Modified tooltip to follow mouse, added Ajax
// "loading" message.

var ajaxtooltip={
	fadeeffect: [true, 300], // enable Fade? [true/false,
								// duration_milliseconds]
	useroffset: [10, 10], // additional x and y offset of tooltip from mouse
							// cursor, respectively
	loadingHTML: '<div style="font-style:italic"><img src="ajaxload.gif" /> Fetching Tooltip...</div>',

	positiontip:function($tooltip, e){
		var docwidth=(window.innerWidth)? window.innerWidth-15 : ajaxtooltip.iebody.clientWidth-15
		var docheight=(window.innerHeight)? window.innerHeight-18 : ajaxtooltip.iebody.clientHeight-15
		var twidth=$tooltip.get(0).offsetWidth
		var theight=$tooltip.get(0).offsetHeight
		var tipx=e.pageX+this.useroffset[0]
		var tipy=e.pageY+this.useroffset[1]
		tipx=(e.clientX+twidth>docwidth)? tipx-twidth-(2*this.useroffset[0]) : tipx // account
																					// for
																					// right
																					// edge
		tipy=(e.clientY+theight>docheight)? tipy-theight-(2*this.useroffset[0]) : tipy // account
																						// for
																						// bottom
																						// edge
		$tooltip.css({left: tipx, top: tipy})
	},

	showtip:function($tooltip, e){
		if (this.fadeeffect[0])
			$tooltip.hide().fadeIn(this.fadeeffect[1])
		else
			$tooltip.show()
	},

	hidetip:function($tooltip, e){
		if (this.fadeeffect[0])
			$tooltip.fadeOut(this.fadeeffect[1])
		else
			$tooltip.hide()
	}
}





var logging = true;

var logger = new Object(); 
logger.info = function(message) {
	$("#logger").append("<p>" + message +"</p>");
}



var activeConditions = new Array(); 

// auxiliary function
function in_array(item,arr) {
	for(p=0;p<arr.length;p++) if (item == arr[p]) return true;
	return false;
}

// This functions parses a classString and extracts conditions that are given by
// "condition-<condition 1> condition-<conditions 2>-..."
function parseConditions(classString) {

	var conditions = new Array();	
	// strip classString by whitespaces;
	var classNames = classString.split(" ");
	for (i in classNames) {
		className = classNames[i];
		if (className.indexOf("condition-") > -1) {
			conditionsString = className.substr(10);
			conditions.push(conditionsString);
		}
	}
	if (logging)
		logger.info("conditions of box: " + conditions);
	return conditions;
}

function renderConditions() {
	$(".conditioned").each(function(){									
		// read classes, find entry that starts with "conditions", read all
		// strings after first -, mutliple entries are separated by "-"
		conditions = parseConditions($(this).attr("class"));			
		visible = true;
		for (i in conditions) {
			condition = conditions[i];
			// alert(i + "+" + conditions.length + " (" + condition + ")-("
			// + activeConditions + ")");
			inArray = in_array(condition, activeConditions); 
			// alert(inArray);
			visible = inArray;
		}
		if (!visible)
			$(this).hide(); 
		else 
			$(this).show();
	});
}

function setCondition(condition) {
	if (logging)
		logger.info("setting condition: " + condition);
	activeConditions.push(condition);
	renderConditions();
}
$(document).ready(function(){
$(".eventButton").each(function() {		
	
	this.eventName = this.getAttribute('title'); 
		var $target=$(this);
	$target.removeAttr('title');
	$target.click(
		function(e){
			setCondition(this.eventName); 
		}
	)
});
});

$(function() {renderConditions();});







	function setSessionDataStoreValue( objectId, pointer, path, value ) {
		if (liquidFacade) liquidFacade.setSessionDataStoreValue( objectId, pointer, path, value, setSessionDataStoreValueCallback );
	}


	function getSessionDataStoreValue( objectId, pointer, path ) {
		if (liquidFacade) liquidFacade.getSessionDataStoreValue( objectId, pointer, path, setSessionDataStoreValueCallback );
	}


	function updateWidget(data, widgetName) {

		$("#"+ widgetName).after(data).next().prev().remove();
	}

	function replaceContent(selector, data) {

		$(selector).after(data).next().prev().remove();
	}


	function setValueAndUpdateWidget(objectid, pointer, path, value, widget) {

		if (liquidFacade) liquidFacade.setSessionDataStoreValue( objectid, pointer, path, value,
			{
			  callback:function(dataFromServer) {
			    updateWidget(dataFromServer, widget);
			  }
		});
	}
	
	
	function loadActionCommandNavigatorSection(navigatorName, sectionName, containerLId, contentProfileLId) {
	
		if (liquidFacade) liquidFacade.getActionCommandNavigatorSection(navigatorName, sectionName, containerLId, contentProfileLId, 
			{
			  callback:function(dataFromServer) {
			  
			  	var containedData = "<div class='body'>" + dataFromServer + "</div>";  
			  	replaceContent("#ajaxActionCommandNavigator div.body", containedData);
			  }
		});
	}
	
	
	function showTimelineEntryBody(objectId, elementSelector, viewMode) {

		if (liquidFacade) liquidFacade.getXhtml(objectId, viewMode, 
			{
			  callback:function(dataFromServer) {
			  	$(elementSelector).html(dataFromServer);
			  }
		});
	}
	
	
	$(document).ready(function(){
		
		ajaxtooltip.iebody=(document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
		var tooltips=[] // array to contain references to all tooltip DIVs on
						// the page
		$('.tooltipped').each(function(index){
			this.targetid = this.getAttribute('title'); 
			this.titleurl=jQuery.trim(this.getAttribute('title').split(':')[1]) // get
																				// URL
																				// of
																				// external
																				// file
			this.titleposition=index+' pos' // remember this tooltip DIV's
											// position relative to its peers
			tooltips.push($('<div class="ajaxtooltip"></div>').appendTo('body'))
			var $target=$(this);
			$target.removeAttr('title');
			$target.hover(
				function(e){ // onMouseover element
					var $tooltip=tooltips[parseInt(this.titleposition)]
					if (!$tooltip.get(0).loadsuccess){ // first time fetching
														// Ajax content for this
														// tooltip?
						$tooltip.get(0).loadsuccess=true;
						$tooltip.html($("#" + this.targetid).html());
						ajaxtooltip.positiontip($tooltip, e)
						ajaxtooltip.showtip($tooltip, e)
					}
					else{
						ajaxtooltip.positiontip($tooltip, e)
						ajaxtooltip.showtip($tooltip, e)
					}
				},
				function(e){ // onMouseout element
					var $tooltip=tooltips[parseInt(this.titleposition)]
					ajaxtooltip.hidetip($tooltip, e)		
				}
			)
			$target.bind("mousemove", function(e){
				var $tooltip=tooltips[parseInt(this.titleposition)]
				ajaxtooltip.positiontip($tooltip, e)
			})
		})
		
		
		$("#myInputField").focus(function(){
		    // Select input field contents
		    this.select();
		});

		// Add this behavior to all text fields
		$("input[type=text]").focus(function(){
		    // Select field contents
		    this.select();
		});
		
		$("#pageHeader .subsubmenu").hide();
		$("#pageHeader .menu2").hoverIntent(
				function(){$("#pageHeader .subsubmenu").slideDown(100);},
				function(){$("#pageHeader .subsubmenu").slideUp(100);}
				);

		$("#participantsOnlineLink").click(
				function(event){event.stopPropagation(); $("#participantsOnline").toggle(); return false;});
		
		
		$(window).resize(function() {
			positionFooter();
		});
		
		if ($("#userUsageStatisticButton")) {

			$("table.userUsageStatistic").hide();
			$("#userUsageStatisticButton").click(function() {$("#userUsageStatistic").toggle();})
		
		}

		positionFooter();

	});
	
	

	

