var ns4;
var ns4;
var op5;
var op6;
var agt;
var mac;
var ie;
var mac_ie;
var moz;
var htmlhttp;
var menuwidth;
var containerposition;
var containeroverflowx;
var containeroverflowy;
var highlighter;
var highlighterodd;

sniffBrowsers();

SetCookie('DocbWeb2ScreenWidth', screen.width, 10000, false);
SetCookie('DocbWeb2ScreenHeight', screen.height, 10000, false);

function GetCookie(cookieName){
	var theCookie = "" + document.cookie;
	var ind = theCookie.indexOf(cookieName);
	if (ind == -1 || cookieName == "") 
		return null;
	var ind1 = theCookie.indexOf(';', ind);
	if (ind1 == -1) 
		ind1 = theCookie.length;
	return unescape(theCookie.substring(ind + cookieName.length + 1, ind1));
}

function SetCookie(cookieName, cookieValue, nDays, escape){
	var today = new Date();
	var expire = new Date();
	if (nDays == null || nDays == 0) {
		if (escape) 
			document.cookie = cookieName + "=" + escape(cookieValue) + ";path=/";
		else 
			document.cookie = cookieName + "=" + cookieValue + ";path=/";
	}
	else {
		expire.setTime(today.getTime() + 3600000 * 24 * nDays);
		
		if (escape) 
			document.cookie = cookieName + "=" + escape(cookieValue) + ";expires=" + expire.toGMTString() + ";path=/";
		else 
			document.cookie = cookieName + "=" + cookieValue + ";expires=" + expire.toGMTString() + ";path=/";
	}
}


function SetDesmarcar(o){
	var child, i;
	
	for (i = 0; i < o.form.childNodes.length; i++) {
		child = o.form.childNodes[i];
		if (child.nodeType == 3) {
			child.nodeValue = 'Desmarcar';
			break;
		}
	}
}

function SetMarcar(o){
	var child, i;
	
	for (i = 0; i < o.form.childNodes.length; i++) {
		child = o.form.childNodes[i];
		if (child.nodeType == 3) {
			child.nodeValue = 'Marcar';
			break;
		}
	}
}


function RecordSelect(o, cookie_name, mfn){
var aux;

	if ((GetCookie(cookie_name) == null) || (GetCookie(cookie_name) == "")) {
		/* Cookie não existe */
		if (o.checked) {
			SetDesmarcar(o);
			SetCookie(cookie_name, mfn + "=checked", 10000, false)
		}
		else {
			SetMarcar(o);
			SetCookie(cookie_name, mfn + "=unchecked", 10000, false)
		}
	}
	else {
		cur_cookievalue = "&" + GetCookie(cookie_name) /* o & é um truque */
		if (o.checked) {
			SetDesmarcar(o);
			if (cur_cookievalue.indexOf("&" + mfn + "=unchecked") != -1) {
				cur_cookievalue = cur_cookievalue.replace("&" + mfn + "=unchecked", "&" + mfn + "=checked");
			}
			else {
				if (cur_cookievalue.indexOf("&" + mfn + "=checked") == -1) {
					cur_cookievalue = cur_cookievalue + "&" + mfn + "=checked";
				}
			}
		}
		else {
			SetMarcar(o);
			if (cur_cookievalue.indexOf("&" + mfn + "=checked") != -1) {
				cur_cookievalue = cur_cookievalue.replace("&" + mfn + "=checked", "&" + mfn + "=unchecked");
			}
			else {
				if (cur_cookievalue.indexOf("&" + mfn + "=unchecked") == -1) {
					cur_cookievalue = cur_cookievalue + "&" + mfn + "=unchecked";
				}
			}
		}
		cur_cookievalue = cur_cookievalue.substring(1,cur_cookievalue.length); /* retirar o & inicial */
		SetCookie(cookie_name, cur_cookievalue, 10000, false)
	}
}


/*function ExportIso2709(BaseName, SessionID, CookieName){
	window.open("Iso2709.asp?Base=" + BaseName + "&SID=" + SessionID + "&Cookie=" + CookieName, "_blank", "height=150,width=400,top=50,left=50");
}

function showDesc(obj){
	if (obj.id == 'simples') 
		window.status = 'Pesquisa simples';
	if (obj.id == 'avançada') 
		window.status = 'Pesquisa avançada';
	if (obj.id == 'índice') 
		window.status = 'Pesquisa por índice';
	if (obj.id == 'thesaurus') 
		window.status = 'Pesquisa por thesaurus';
	if (obj.id == 'cdu simples') 
		window.status = 'Pesquisa temática simples';
	if (obj.id == 'cdu avançada') 
		window.status = 'Pesquisa temática avançada';
	if (obj.id == 'links') 
		window.status = 'Pequisa de links';
	if (obj.id == 'favoritos') 
		window.status = 'Favoritos';
	if (obj.id == 'notícias') 
		window.status = 'Notícias';
	
	return true;
}


function hideDesc(){
	window.status = '';
}


function ChangeImage(obj, image){
	obj.src = image;
}



function CommentWindow(WebMail){
	window.open("comment.asp?Email=" + WebMail, "_blank", "height=300,width=450,top=50,left=50");
}



function doTooltip(e, msg){
	if (typeof Tooltip == "undefined" || !Tooltip.ready) 
		return;
	Tooltip.show(e, msg);
}

function hideTip(){
	if (typeof Tooltip == "undefined" || !Tooltip.ready) 
		return;
	Tooltip.hide();
}
*/

function ToggleViewItems(o, mfn){
	var divelement, child, i, aelement;
	
	aelement = document.getElementById("ItemLink" + mfn);
	
	divelement = document.getElementById("sitexemplar" + mfn);
	
	if (divelement != null) {
		if (divelement.style.display == "") {
			divelement.style.display = "none";
			
			if (aelement.firstChild != null) 
				if (aelement.firstChild.firstChild != null) 
					aelement.firstChild.firstChild.nodeValue = 'Ver informação de exemplares';
			
		}
		else {
			divelement.style.display = "";
			
			if (aelement.firstChild != null) 
				if (aelement.firstChild.firstChild != null) 
					aelement.firstChild.firstChild.nodeValue = 'Ocultar informação de exemplares';
			
		}
	}
	
}
/*
function findPosY(obj){
	var curtop = 0;
	
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	else {
		if (obj.y) {
			curtop += obj.y;
		}
	}
	return curtop;
}


function ScrollToElement(theElement){
	var selectedPosX = 0;
	var selectedPosY = 0;
	
	while (theElement != null) {
		selectedPosX += theElement.offsetLeft;
		selectedPosY += theElement.offsetTop;
		theElement = theElement.offsetParent;
	}
	
	window.scrollTo(selectedPosX, selectedPosY - document.body.clientHeight);
}
*/

function getElementHeight(Elem){
	var yPos;
	
	if (ns4) {
		var elem = getObjNN4(document, Elem);
		return elem.clip.height;
	}
	else {
		if (document.getElementById) {
			var elem = document.getElementById(Elem);
		}
		else 
			if (document.all) {
				var elem = document.all[Elem];
			}
		if (elem != null) {
			if (op5) {
				yPos = elem.style.pixelHeight;
			}
			else {
				yPos = elem.offsetHeight;
			}
		}
		return yPos;
	}
}


function setElementHeight(Elem, NewHeight){
	if (ns4) {
		var elem = getObjNN4(document, Elem);
		elem.clip.height = NewHeight;
	}
	else {
		if (document.getElementById) {
			var elem = document.getElementById(Elem);
		}
		else 
			if (document.all) {
				var elem = document.all[Elem];
			}
		if (elem != null) {
			if (op5) {
				elem.style.pixelHeight = NewHeight;
			}
			else {
				if (NewHeight < 300) 
					NewHeight = 300;
				elem.style.height = NewHeight;
			}
		}
	}
}

/*
function getElementWidth(Elem){
	var xPos = -1;
	
	if (ns4) {
		var elem = getObjNN4(document, Elem);
		return elem.clip.width;
	}
	else {
		if (document.getElementById) {
			var elem = document.getElementById(Elem);
		}
		else 
			if (document.all) {
				var elem = document.all[Elem];
			}
		if (elem != null) {
			if (op5) {
				xPos = elem.style.pixelWidth;
			}
			else {
				xPos = elem.offsetWidth;
			}
		}
		return xPos;
	}
}
*/


function sniffBrowsers(){
	ns4 = document.layers;
	op5 = (navigator.userAgent.indexOf("Opera 5") != -1) || (navigator.userAgent.indexOf("Opera/5") != -1);
	op6 = (navigator.userAgent.indexOf("Opera 6") != -1) || (navigator.userAgent.indexOf("Opera/6") != -1);
	agt = navigator.userAgent.toLowerCase();
	mac = (agt.indexOf("mac") != -1);
	ie = (agt.indexOf("msie") != -1);
	moz = (agt.indexOf("firefox") != -1);
	mac_ie = mac && ie;
}

function loadHTMLDoc(url, onready){
	try {
		htmlhttp = new XMLHttpRequest();
	} 
	catch (ee) {
		try {
			htmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) {
			try {
				htmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch (E) {
				htmlhttp = false;
			}
		}
	}
	htmlhttp.onreadystatechange = onready;
	htmlhttp.open("GET", url, true);
	htmlhttp.send(null);
}

function ToggleStyle(divel, mode){
	if (mode == 0) 
		divel.className = "buttonnormal";
	if (mode == 1) 
		divel.className = "buttonmouseover";
	if (mode == 2) 
		divel.className = "buttonmousedown";
}

function SubmitForm(formname){
	var f = document.forms;
	
	for (i = 0; i < f.length; i++) {
		if (f[i].name == formname) {
			f[i].submit();
			break;
		}
	}
}

/*
function ParentForm(obj){
	if (obj.parentElement) {
		while (obj.parentElement) {
			if (obj.tagName == 'FORM') 
				return obj;
			obj = obj.parentElement;
		}
	}
	return obj;
}

*/

function LoadHTMLDocEx(url, target, func){

	function whenDone(){
		if (req.readyState == 4) {
			if (req.status == 200) {
				document.getElementById(target).innerHTML = req.responseText;
				if (func != '') 
					eval(func + "()");
			}
			else {
				document.getElementById(target).innerHTML = req.statusText;
			}
		}
	}
	
	try {
		var req = new XMLHttpRequest();
	} 
	catch (ee) {
		try {
			var req = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) {
			try {
				var req = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch (E) {
				var req = false;
			}
		}
	}
	if (req) {
		req.onreadystatechange = function(){
			whenDone();
		};
		req.open("GET", url, true);
		req.send(null);
	}
}


function ajaxPost(url,params,target,func){

	function whenDone(){
		if (req.readyState == 4) {
			if (req.status == 200) {
				document.getElementById(target).innerHTML = req.responseText;
				if (func != '') 
					eval(func + "()");
			}
			else {
				document.getElementById(target).innerHTML = req.statusText;
			}
		}
	}
	
	try {
		var req = new XMLHttpRequest();
	} 
	catch (ee) {
		try {
			var req = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) {
			try {
				var req = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch (E) {
				var req = false;
			}
		}
	}
	if (req) {
		req.onreadystatechange = function(){
			whenDone();
		};
		req.open("POST", url, true);
		req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		req.setRequestHeader("Content-length", params.length);
		req.setRequestHeader("Connection", "close");
		req.send(params);
	}
}

/*
function ExecAsp(url){

	try {
		var req = new XMLHttpRequest();
	} 
	catch (ee) {
		try {
			var req = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) {
			try {
				var req = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch (E) {
				var req = false;
			}
		}
	}
	if (req) {
		req.open("GET", url, false);
		req.send(null);
	}
}
*/


/* só funciona chamado depois da tag <body> */
function clientWidth(){
	if (document.compatMode && document.compatMode != "BackCompat") 
		return (document.documentElement.clientWidth);
	else 
		return (document.body.clientWidth);
}

/* só funciona chamado depois da tag <body> */
function clientHeight(){
	if (document.compatMode && document.compatMode != "BackCompat") 
		return (document.documentElement.clientHeight);
	else 
		return (document.body.clientHeight);
}

/*
function screensize(){
	if (ie) {
		cwidth = document.documentElement.offsetWidth;
		cheight = document.documentElement.offsetHeight;
	}
	if (moz) {
		cwidth = document.body.clientWidth;
		cheight = document.body.clientHeight;
	}
}
*/

function grayOut(vis, options) {
  // Pass true to gray out screen, false to ungray
  // options are optional.  This is a JSON object with the following (optional) properties
  // opacity:0-100         // Lower number = less grayout higher = more of a blackout 
  // zindex: #             // HTML elements with a higher zindex appear on top of the gray out
  // bgcolor: (#xxxxxx)    // Standard RGB Hex color code
  // grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});
  // Because options is JSON opacity/zindex/bgcolor are all optional and can appear
  // in any order.  Pass only the properties you need to set.
  var options = options || {}; 
  var zindex = options.zindex || 50;
  var opacity = options.opacity || 70;
  var opaque = (opacity / 100);
  var bgcolor = options.bgcolor || '#000000';
  var dark=document.getElementById('darkenScreenObject');
  if (!dark) {
    // The dark layer doesn't exist, it's never been created.  So we'll
    // create it here and apply some basic styles.
    // If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
    var tbody = document.getElementsByTagName("body")[0];
    var tnode = document.createElement('div');           // Create the layer.
        tnode.style.position='absolute';                 // Position absolutely
        tnode.style.top='0px';                           // In the top
        tnode.style.left='0px';                          // Left corner of the page
        tnode.style.overflow='hidden';                   // Try to avoid making scroll bars            
        tnode.style.display='none';                      // Start out Hidden
        tnode.id='darkenScreenObject';                   // Name it so we can find it later
    tbody.appendChild(tnode);                            // Add it to the web page
    dark=document.getElementById('darkenScreenObject');  // Get the object.
  }
  if (vis) {
    // Calculate the page width and height 
/*    if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) ) {
        var pageWidth = document.body.scrollWidth+'px';
        var pageHeight = document.body.scrollHeight+'px';
    } else if( document.body.offsetWidth ) {
      var pageWidth = document.body.offsetWidth+'px';
      var pageHeight = document.body.offsetHeight+'px';
    } else {*/
       var pageWidth='100%';
       var pageHeight='100%';
/*    }   */
    //set the shader to cover the entire page and make it visible.
    dark.style.opacity=opaque;                      
    dark.style.MozOpacity=opaque;                   
    dark.style.filter='alpha(opacity='+opacity+')'; 
    dark.style.zIndex=zindex;        
    dark.style.backgroundColor=bgcolor;  
    dark.style.width= pageWidth;
    dark.style.height= pageHeight;
    dark.style.display='block';                          
  } else {
     dark.style.display='none';
  }
}


Element.implement({
  //implement show
  show: function() {
     this.setStyle('display','');
  },
  //implement hide
  hide: function() {
      this.setStyle('display','none');
  }
});


var DropdownMenu = new Class({
	initialize: function(element){
  
    if (element) {
      $A($(element).childNodes).each(function(el){
        if (el.nodeName.toLowerCase() == 'li') {
          $A($(el).childNodes).each(function(el2){
            if (el2.nodeName.toLowerCase() == 'ul') {
              
              $(el2).hide();
              
              el.addEvent('mouseover', function()
              {
                el2.show();
                return false;
              });

              el.addEvent('mouseout', function()
              {
                el2.hide();
              });
              

              new DropdownMenu(el2);
            }
          });
          
          if ((el.className.toLowerCase() == 'dropdown') || (el.className.toLowerCase() == 'active')) {
          }
          else {
          }
        }
      });
    }
		return this;
	}
});


window.addEvent('domready', function() {

	// change tips 
 
  $$('.cotatip').each(function(element,index) {
    var title = element.get('title');
    element.store('tip:title', title);
    element.store('tip:text', CotaInfo(title));
  });  
  
  // cota tip 

  var cotatip = new Tips('.cotatip', {
/*			initialize: function() {
				this.fx = new Fx.Style(this.toolTip, 'opacity', { duration: 500, wait: false }).set(0);
			},
			onShow: function(toolTip) {
				this.fx.start(1);
			},
			onHide: function(toolTip) {
				this.fx.start(0);
			}*/
    });    
		
	//call multiBox
	var myMultiBox = new multiBox({
		onOpen: function(el) {

		  // desligar o fixed position do #container, o overflow-x e overflow-y
		  try {
  			containerposition = $('container').getStyle('position');
	  		$('container').setStyle('position','inherit');
		  	containeroverflowx = $('container').getStyle('overflow-x');
			  $('container').setStyle('overflow-x','inherit');
			  containeroverflowy = $('container').getStyle('overflow-y');
			  $('container').setStyle('overflow-y','inherit');
			} catch (e){
			}
		},
		onClose: function(){
			if (containerposition) {
				$('container').setStyle('position',containerposition);
			}
			if (containeroverflowx) {
				$('container').setStyle('overflow-x',containeroverflowx);
			}			
			if (containeroverflowy) {
				$('container').setStyle('overflow-y',containeroverflowy);
			}			
		},
		mbClass: '.mb',//class you need to add links that you want to trigger multiBox with (remember and update CSS files)
		container: $(document.body), //where to inject multiBox
		descClassName: 'multiBoxDesc',//the class name of the description divs
		path: 'multibox_files/',//path to mp3 and flv players
		useOverlay: true,//use a semi-transparent background. default: false;
    showControls: document.mmedia,
    showNumbers: document.mmedia,
		recalcTop: true//,subtract the height of controls panel from top position
	});	
	
	smartHoverBox(0, 120, 0, '_smarthbox', 'smarthbox_close');
	
	$(document.body).getElements('div.mmpreviewbox').each(function(el){
		var NewParent = $('mmpreviewboxparent');
		if (NewParent) 
			el.inject(NewParent);
	});
	
	// acrescenter o "vêr multimedia" quando as imagens não cabem no div hidden
	$(document.body).getElements("div.mmsection").each(function(el){
		var mmviewmore_id = el.id.replace('mmsection','mmviewmore');
		el.setStyle("overflow","auto");
		if (el.scrollHeight>el.clientHeight) $(mmviewmore_id).setStyle("display","block");
		if (el.scrollWidth>el.clientWidth) $(mmviewmore_id).setStyle("display","block");
		el.setStyle("overflow","hidden");
	});	

  highlighter = new Highlighter({
      elements: 'div.record',
      className: 'highlight',
      autoUnhighlight: false
  });  
  
  highlighterodd = new Highlighter({
      elements: 'div.recordodd',
      className: 'highlight',
      autoUnhighlight: false
  });  
	
});


window.addEvent('resize', function(e){
	var menuwidth = 0;

  if ($('dropdownmenu'))
  {
    $('dropdownmenu').getElements('li').each(function(el){
      if (el.getParent().id=='dropdownmenu')
      { 
        if ((el.id!='leftmargin') && (el.id!='rightmargin'))
          menuwidth+=el.getStyle('width').toInt();
      }
    });
    
		var menuleft = document.body.clientWidth / 2 - (menuwidth / 2).toInt();
		if (menuleft < 0) 
			menuleft = 0;

    var menuright = document.body.clientWidth-menuwidth-menuleft-2;
    if (menuright < 0) menuright=0;
    if (menuleft>0)
      $('dropdownmenucontent').setStyle('width', document.body.clientWidth + 'px');
    else
      $('dropdownmenucontent').setStyle('width', menuwidth + 'px');
    $('rightmargin').setStyle('width',menuright);
    $('leftmargin').setStyle('width',menuleft);
	}		
	
	var endformruler = $('endformruler');
	if (endformruler)
	{
		var aux = window.getHeight() - $('endformruler').getTop()-50;
		aux = $('baselist').getStyle('height').toInt() + aux;
		if (aux < 65) aux = 65;
		if (aux < maxbaselistlen)
			$('baselist').setStyle('overflow-y', 'scroll');
		else
		{	
			aux = maxbaselistlen;
			$('baselist').setStyle('overflow-y', 'auto');
		}
		$('baselist').setStyle('height', aux + 'px');
	}

});


window.addEvent('load', function(e) {

  if ($('dropdownmenu'))
  {
    new DropdownMenu($('dropdownmenu'))

    var menuwidth = 0;
    
    $('dropdownmenu').getElements('li').each(function(el){
      if (el.getParent().id=='dropdownmenu')
      { 
        if ((el.id!='leftmargin') && (el.id!='rightmargin'))
          menuwidth+=el.getStyle('width').toInt();
      }
    });

    var menuleft = document.body.clientWidth / 2 - (menuwidth / 2).toInt();
    if (menuleft < 0)
      menuleft = 0;
    
    var menuright = document.body.clientWidth-menuwidth-menuleft-2;
    if (menuright < 0) menuright=0;
    if (menuleft>0)
      $('dropdownmenucontent').setStyle('width', document.body.clientWidth + 'px');
    else
      $('dropdownmenucontent').setStyle('width', menuwidth + 'px');
    $('rightmargin').setStyle('width',menuright);
    $('leftmargin').setStyle('width',menuleft);
    
  }

  var endformruler = $('endformruler');
  if (endformruler) {
    var aux = window.getHeight() - $('endformruler').getTop() - 50;
    aux = $('baselist').getStyle('height').toInt() + aux;
    if (aux < 65) aux = 65;
    if (aux < maxbaselistlen)
      $('baselist').setStyle('overflow-y', 'scroll');
    else {
      aux = maxbaselistlen;
      $('baselist').setStyle('overflow-y', 'auto');
    }
    $('baselist').setStyle('height', aux + 'px');
  }
	
	/////
		
	$(document.body).getElements("div.mmsection_outer").each(function(el){
	
		var mfn = el.id.replace('mmsection_outer_','');
		
		new SlideItMoo({
			overallContainer: 'mmsection_outer_'+mfn,
			elementScrolled: 'mmsection_inner_'+mfn,
			thumbsContainer: 'mmsection_items_'+mfn,		
			itemsVisible:$('mmsection_slidelimit').getStyle('width').toInt(),
			itemsSelector: '.mmthumbcontainer',
			itemWidth: $('mmsection_slide_itemwidth').getStyle('width').toInt(),
			duration:300,
			showControls:1});
		
	});
	
	// acrescenter o "vêr multimedia" quando as imagens não cabem no div hidden
	$(document.body).getElements("div.mmsection_inner").each(function(el){
		var mmviewmore_id = el.id.replace('mmsection_inner','mmviewmore');
		el.setStyle("overflow","auto");
		if (el.scrollHeight>el.clientHeight) $(mmviewmore_id).setStyle("display","block");
		if (el.scrollWidth>el.clientWidth) $(mmviewmore_id).setStyle("display","block");
		el.setStyle("overflow","hidden");
	});

	// acrescentar "..." ao comentário quando este não cabe no div hidden
/*	$(document.body).getElements("div.mmthumb_commentcontainer").each(function(el){
		var aux='';
		el.setStyle("overflow","auto");
		while (el.scrollHeight>el.clientHeight)
		{
			aux = $(el).getElement('a.mmthumb_comment').innerHTML;
			$(el).getElement('a.mmthumb_comment').innerHTML = aux.substring(0,aux.length-3);
			console.log(el.scrollHeight);
			console.log(el.clientHeight);
		}
		if (aux!='') 
		{
			aux = $(el).getElement('a.mmthumb_comment').innerHTML;
			$(el).getElement('a.mmthumb_comment').innerHTML = aux.substring(0,aux.length-3) + '...';
		}
		el.setStyle("overflow","hidden");
	});*/
	
});


function RSSList()
{
	window.open("rsslist.asp","_blank","height=600,width=400,top=50,left=50");
}


function OpenUrl(url)
{
	window.location = url;
}


// ====================================================================
//       URLEncode and URLDecode functions
//
// Copyright Albion Research Ltd. 2002
// http://www.albionresearch.com/
//
// You may copy these functions providing that 
// (a) you leave this copyright notice intact, and 
// (b) if you use these functions on a publicly accessible
//     web site you include a credit somewhere on the web site 
//     with a link back to http://www.albionresearch.com/
//
// If you find or fix any bugs, please let us know at albionresearch.com
//
// SpecialThanks to Neelesh Thakur for being the first to
// report a bug in URLDecode() - now fixed 2003-02-19.
// And thanks to everyone else who has provided comments and suggestions.
// ====================================================================
function URLEncode( plaintext)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	//var plaintext = document.URLForm.F1.value;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    /*alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );*/
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

/*	document.URLForm.F2.value = encoded;
  document.URLForm.F2.select();*/
	return encoded;
};

function ToggleMenu()
{
  
	if ($('header').getStyle('display') == 'block')
	{
    var background = $(document.body).getStyle('background');
    $(document.body).setStyle('background','transparent');
		$('header').setStyle('display','none');
		var containerpos = $('container').getStyle('top');
		$('container').setStyle('top',0);
	}
	else
	{
    $(document.body).setStyle('background',background);
		$('header').setStyle('display','block');
		$('container').setStyle('top',containerpos);
	}
	
}

var Highlighter = new Class({
			
	/* implements */
	Implements: [Options],

	/* options */
	options: {
		autoUnhighlight: true,
		caseSensitive: false,
		elements: '*',
		className: '',
		onlyWords: false,
		tag: 'span'
	},
	
	/* initialization */
	initialize: function(options) {
		/* set options */
		this.setOptions(options);
		this.elements = $$(this.options.elements);
		this.words = [];
	},
	
	/* directs the plugin to highlight elements */
	highlight: function(words,elements,className) {
		
		/* figure out what we need to use as element(s) */
		var elements = $$(elements || this.elements);
		var klass = className || this.options.className;
		if (words.constructor === String) { words = [words]; }
		
		/* auto unhighlight old words? */
		if(this.options.autoUnhighlight) { this.unhighlight(); }
		
		/* set the pattern and regex */
		var pattern = this.options.onlyWords ? '\\b' + pattern + '\\b' : '(' + words.join('|') + ')';
		var regex = new RegExp(pattern, this.options.caseSensitive ? '' : 'i');
		
		/* run it for each element! */
		elements.each(function(el) { this.recurse(el,regex,klass); },this);
		
		/* make me chainable! */
		return this;
	}, 
	
	/* unhighlights items */
	unhighlight: function(words) {
		//var selector = this.options.tag + (word ? '[rel=' + word + ']' : '');
		if (words.constructor === String) { words = [words]; }
		words.each(function(word) {
			word = (this.options.caseSensitive ? word : word.toUpperCase());
			if(this.words[word]) {
				var elements = $$(this.words[word]);
				elements.set('class','');
				elements.each(function(el) {
					var tn = document.createTextNode(el.get('text'));
					el.getParent().replaceChild(tn,el);
				});
			}
		},this);
		return this;
	},
	
	/* recursed function */
	recurse: function(node,regex,klass) {
			if (node.nodeType === 3) {
				var match = node.data.match(regex);
				if (match) {
					/* new element */
					var highlight = new Element(this.options.tag);
					highlight.addClass(klass);
					var wordNode = node.splitText(match.index);
					wordNode.splitText(match[0].length);
					var wordClone = wordNode.cloneNode(true);
					highlight.appendChild(wordClone);
					wordNode.parentNode.replaceChild(highlight, wordNode);
					highlight.set('rel',highlight.get('text'));
					var comparer = highlight.get('text');
					if(!this.options.caseSensitive) { comparer = highlight.get('text').toUpperCase(); }
					if(!this.words[comparer]) { this.words[comparer] = []; }
					this.words[comparer].push(highlight);
					return 1;
				}
			} else if ((node.nodeType === 1 && node.childNodes) && !/(script|style)/i.test(node.tagName) && !(node.tagName === this.options.tag.toUpperCase() && node.className === klass)) {
				for (var i = 0; i < node.childNodes.length; i++) {
					i += this.recurse(node.childNodes[i],regex,klass);
				}
			}
			return 0;
		}
	});

  
  
/*  
var startPageTime = $time();
 
window.addEvent('domready', function() {
	var total = $time() - startPageTime;
  
	$('container').appendText('Loading time (domready)' + total + 'ms.');
 
});
 
window.addEvent('load', function() {
	var total = $time() - startPageTime;
  
  $('container').appendText('Loading time (load:with images)' + total + 'ms.');
});*/