// General JS Functions
// Copyright 2006 APS web.services GmbH
// Author: Stefan Pasel (sp@aps-web.de)

if (!window.console) {
	if (!window.console || !console.firebug) {
	    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
	    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

	    window.console = {};
	    for (var i = 0; i < names.length; ++i) {
	        window.console[names[i]] = function() {};
	    }
	}
}

Ajax.Responders.register({
	onCreate: function() {
		if(Ajax.activeRequestCount > 0)
		{
			if($('ajax_indicator'))
				Effect.Appear('ajax_indicator',{duration: 0.25, queue: 'end'});

			//if ($('ajax_status'))
			//	$('ajax_status').className='loading';
		}
	},
	onComplete: function() {
		if(Ajax.activeRequestCount == 0)
		{
			if($('ajax_indicator'))
				Effect.Fade('ajax_indicator',{duration: 0.25, queue: 'end'});

			if ($('ajax_status'))
				$('ajax_status').className='';
		}
	}
});


	function addLoadEvent(func) {
		var oldonload = window.onloadEvent;
		if (typeof window.onloadEvent != 'function') {
			window.onloadEvent = func;
		} else {
			window.onloadEvent = function() {
				oldonload();
				func();
			}
		}
	}

	//Dean Edwards/Matthias Miller/John Resig
	function init() {
	    if (arguments.callee.done) return;
	    arguments.callee.done = true;
	    if (_timer) clearInterval(_timer);
	    try{
				screencheck();
				screencheck('h');
			}catch(e){};
			window.onloadEvent();
	};

/**
* Ajax Link
* @param id-string/element
* @param id-string callback element
*/
var al_cache = $H({});
function al(el,cb_el,cache_id)
{
	var request_url = $(el).href;
	var PDATA = "ajax=1&cache_id="+ cache_id +"&cb_el=" + cb_el;
	var s = $(el).parentNode.parentNode;
	
	if(s.hasChildNodes())
	{
		s = s.childNodes;
		for(var i=0;i<s.length;i++)
			s[i].firstChild.className = '';
	}
	else
	{
		//No Children (Wrong formatting or whatever)
	}
	$(el).className = 'selected';

	var found = al_cache.find(function(v){
			if(v[0]==cache_id){return true;}else{return false;}
			});
	if(cache_id && found)
	{
		cb_fill(found[1].ajax,found[1].json);
	}
	else
	{
		new Ajax.Request( request_url,
					     				{
					     					method:'post',
					     					parameters: PDATA,
					     					evalScripts: true,
					     					onComplete: cb_fill,
					     					onFailure: function()
					     					{
					     						self.location.href = request_url;
					     					}
					     				} );

		//Signal Loading..
		//
		var bo = $('box_content');
		if (bo)
		{
			bo.innerHTML = '<div id="ajax_status" class="loading"></div>';
		}
		var as = $('ajax_status');
		if (as)
		{
			as.className = 'loading';
			document.getElementsByTagName('body')[0].className = 'loading';
		}
	}
	return false;
}

/**
* Ajax Callback Fill
* @param ajax object
* @param json id-string callback element
*/
function cb_fill(ajax,json)
{
	el_id = json.cb_el;
  if (json && json.cb_tab)
  {
    var s = $(json.cb_tab).parentNode.parentNode;
    if(s.hasChildNodes())
	  {
	  	try{
		  s = s.childNodes;
		  for(var i=0;i<s.length;i++)
			  s[i].firstChild.className = '';
			}catch(e){}
	  }
  }

  if(json && json.cb_fkt)
  {
  	json.cb_fkt();
  }

  Element.addClassName($(json.cb_tab),'selected');
	var newhtml = ajax.responseText;
	if (el_id)
	{
		$(el_id).innerHTML = newhtml;
		newhtml.evalScripts();
	}
	else
	{
		/* alert('JSON missing ('+el_id+')? Response was:' +newhtml); */
		return false;
	}
	var as = $('ajax_status');
	if (as)
	{
		as.className = '';
		document.getElementsByTagName('body')[0].className = '';
	}
	if (json && json.cache_id)
	{
		var found = al_cache.find(function(v){
			if(v[0]==json.cache_id){return true;}else{return false;}
			});
		if(!found)
		{
			eval('var cache_obj = {'+json.cache_id+':{ajax:ajax,json:json}}');
			al_cache = al_cache.merge($H(cache_obj));
		}
	}
}

function quick_tab(tabelement, tab_div_id)
{
  var tabID = tabelement.href.match(/#(\w.+)/)[1];
  $$("#"+tab_div_id+" .page").each(function(my_element){
    if (Element.hasClassName(my_element,tabID))
      Element.show(my_element);
    else
      Element.hide(my_element);

  });
  $$("#"+tab_div_id+" .tab").each(function(my_element){
      Element.removeClassName(my_element,'selected');
  });
  Element.addClassName(tabelement,'selected')
}

function toggle_class(class_name)
{
    $$(class_name).each(function(my_element){
       if (my_element.style.display=='block')
         my_element.style.display='none';
       else
         my_element.style.display='block';
  });
}

function collapse_box(id) {
    if ($(id).hasClassName('collapsed')) {
      $(id).removeClassName('collapsed');
    } else {
      $(id).addClassName('collapsed');
    }
}

function fill_underlying_select ()
{
    var u_select = $('header_underlying_select');
    if (u_select.length<=1)   // Fill only if empty
    {
      if (uv)
        for (var ISIN in uv)
        {
          u_select.options.add( new Option(uv[ISIN],ISIN),9999);
        }
    }
}

// CHART Functions ------------------------------------------------------------------

/**
* Group Image Functions
*
*/
var current_chart_base_url;
var imagectrl = Class.create();
imagectrl.prototype = {
	initialize:function(image_id)
	{
		this.image = $(image_id);
		this.src = this.image.src;
	},
	reload_chart:function(newurl){
    if (!newurl)
      newurl=current_chart_base_url;
    newurl = newurl + this.get_chart_options();
    //this.tmp_image= new Image();
    //this.tmp_image.onload = this.check_display.bind(this);
    //this.tmp_image.onerror = this.tmp_image.onload;
    //this.tmp_image.onabort = this.tmp_image.onload;
    //this.tmp_image.src=newurl;
    this.src=newurl;
    new Effect.Fade(this.image,{duration:0.4});
   	window.setTimeout(this.check_display.bind(this),350);
	},
	get_chart_options:function(){
	  var chart_params="";

	  if ($("chart_show_underlying") && $("chart_relative_scale"))
	  {
		  if ($("chart_show_underlying").checked)
		  {
		    chart_params+="&show_underlying=1";
		    $("chart_relative_scale").checked=true;
		    $("chart_relative_scale").disabled=true;
		  } else {
		    $("chart_relative_scale").disabled=false;
		  }

		  if ($("chart_relative_scale").checked)
		    chart_params+="&scaling=rel";
		}
	  var now = new Date();
	  chart_params+='&time='+now.getTime();

	  return (chart_params);
	},
	check_display:function(){
		this.image.onload = this.display.bind(this);
		this.image.src = this.src;
		//if(this.tmp_image.complete)
		//	window.setTimeout(this.display.bind(this),10);
		//else
		//{
		//	this.image.src = '/images/icons/spacer.gif';
		//	window.setTimeout(this.display.bind(this),300);
		//}
	},
	display:function(){
		//this.image.src = this.src;
		//if(!Element.visible(this.image))
		new Effect.Appear(this.image,{duration:0.5});
		this.tmp_image = null;
	},
	img_refresh:function(){
		var t = new Date();
		if (!this.src.match(/(&rs=|\?rs=)/))
			this.src += ((this.src.match(/\?/)) ? '&rs=' : '?rs=') + t.getTime();
		else
			this.src = this.src.replace(/rs=\d+/,'rs='+t.getTime());
		t = null;
		this.tmp_image= new Image();
    this.tmp_image.src=this.src;
    window.setTimeout(this.display.bind(this),10);
	},
	auto_reload:function(frequency){
	 	this.pe = new PeriodicalExecuter(this.img_refresh.bind(this),frequency);
	}
}

var chartctrl = false;
function image_tab(el, image_id, newurl){
 		var s = $(el).parentNode.parentNode;
		if(s.hasChildNodes())
		{
			s = s.childNodes;
			for(var i=0;i<s.length;i++)
				s[i].firstChild.className = '';
		}
		else
		{
			//No Children (Wrong formatting or whatever)
		}
		$(el).className = 'selected';
		if (!chartctrl){
		chartctrl = new imagectrl(image_id);
		}
	  chartctrl.reload_chart(newurl);
		current_chart_base_url=newurl;
    return true;
}

function highlight_performance_col(class_id, number_id)
{
	element_list = $('performance_table').getElementsByTagName('td');
	$A(element_list).each( function(element){
	if(Element.hasClassName(element,class_id+'_'+number_id))
		Element.addClassName(element,'on');
	else
		Element.removeClassName(element,'on');
	});
}

var gotourl;

function goto_url(url)
{
  if (url)
    document.location=url;
  else if (gotourl)
    document.location=gotourl;
}

function popup_confirm($msg, $url, $language)
{
 if (typeof $language == "undefined") {
    $language = "en";
  }
  gotourl=$url;
  new LITBox($msg, {type:'confirm', func:goto_url, overlay:true, height:130, width:240, resizable:false, draggable: false, language: $language});
  return false;
}


function urlDecode(str){
    str=str.replace(new RegExp('\\+','g'),' ');
    return unescape(str);
}

/* AUTOCOMPLETE */
//XML End
/* vim:ts=4:sts=4:sw=2:noai:noexpandtab
 *
 * Auto-complete client side javascript.
 * Copyright (c) 2005 Steven McCoy <fnjordy@gmail.com> (http://fnjordy.cus.org.uk/auto/)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

/* format of constructor is overloaded:
 * AC(<type>, <id>, <submit callback>)
 * AC(<type>, <id>)
 * AC(<id>)
 */
function AC(id) {
/* find search type */
	if (arguments.length > 1) {
		this.type = arguments[0];
		id = arguments[1];
	} else {
		this.type = id;
	}

/* input element we are autocompleting on */
	this.obj = document.getElementById(id);
	//this.obj.value = '';

/* base url to send request too */
	this.url = '/index.php';

/* function to call when option selected */
	this.submit_callback = (arguments.length > 2) ? arguments[2] : null;

/* popup layer we will display results in */
	this.div = document.createElement('DIV');
	this.div.className = 'ac_menu';
	this.div.style.visibility = 'hidden';
	this.div.style.position = 'absolute';
	this.div.style.zIndex = 15000;//UDM starts with 1000
	this.div.style.width = this.obj.offsetWidth - 2 + "px";

	this.div.style.left = this.total_offset(this.obj,'offsetLeft') + "px";
	this.div.style.top = this.total_offset(this.obj,'offsetTop') + this.obj.offsetHeight - 1 + "px";

/* tie to input element */
	this.obj.parentNode.insertBefore(this.div, this.obj.nextSibling);

/* iframe for non-XmlHttpRequest() browsers */
	this.iframe = null;

/* install event handlers */
	this.obj.onkeydown = this.onkeydown;
	this.obj.onkeyup = this.onkeyup;
	this.obj.onkeypress = this.onkeypress;
	this.obj.onblur = function() { this.AC.close_popup(); }

	this.obj.AC = this;		/* self reference */
	this.selected_option = null;	/* the currently selected option */

	this.request = null;		/* http request object */
	this.cache = new Array();	/* cache of results from server */
	this.typing = false;		/* whether user is still typing */
	this.typing_timeout = 30;
	this.sending_timeout = 30;

	this.search_term = null;	/* current search term  */
	this.previous_term = null;	/* previous search term */
	this.searched_term = null;	/* search from keyboard */

	this.last_input = null;		/* previous typed entry */

/* Unicode inputs require polling of the input control for updates */
	this.poll_input = false;

/* update extern mapping array for rpc reply */
	_ac_map_add(this);
}

AC.prototype.enable_unicode = function() {
	this.poll_input = true;
	_ac_key_check(this,this.typing_timeout);
}

AC.prototype.total_offset = function(element, property) {
	var total = 0;
	while (element) {
		total += element[property];
		element = element.offsetParent;
	}
	return total;
}

/* hide popup and cleanup */
AC.prototype.close_popup = function() {
	this.div.style.visibility = 'hidden';

/* no selected item, no typing, and close any pending request */
	this.selected_option = null;
	this.typing = false;
	this.search_term = null;
	this.previous_term = null;
}

/* create object for rpc call */
AC.prototype.XMLHttpRequest = function() {
	var request = null;
	if (typeof XMLHttpRequest != 'undefined') {
		request = new XMLHttpRequest();
	} else {
		try {
			request = new ActiveXObject('Msxml2.XMLHTTP')
		} catch(e) {
			try {
				request = new ActiveXObject('Microsoft.XMLHTTP')
			} catch(e) {
				request = null
			}
		}
	}
	return request;
}

/* helper functions to process typing timer */
var _ac_key_thunk = new Array();
function _ac_key_thunk_call(id) {
	if (_ac_key_thunk[id]) {
		var ac = _ac_key_thunk[id][1];

/* now check as if onkeyup() was called */
/* first find unselected text */
		var unselected = ac.obj.value;
		if (document.selection) {
			var range = document.selection.createRange();
			if (range) {
/* to limit the execution this would be nice, but parentElement() not supported in Opera */
//			if (range && range.parentElement && range.parentElement() == ac.obj) {
				var length = unselected.length - range.text.length;
				if (length > 0) {
					unselected = unselected.substring(0, length);
				}
			}
		} else if (ac.obj.setSelectionRange) {
			var length = ac.obj.selectionEnd - ac.obj.selectionStart;
			if (length > 0)
				unselected = unselected.substring(0,ac.obj.selectionStart);
		}

		if (unselected != ac.last_input) {
			if (unselected.length > 0) {
				ac.searched_term = unselected;
				ac.suggest(ac.searched_term);
			} else {
				_ac_cancel(ac);
				ac.close_popup();
			}
			ac.last_input = unselected;
		}

/* re-install timer for polling */
		if (ac.poll_input) {
			_ac_key_thunk[id][2] = setTimeout("_ac_key_thunk_call("+id+")",ac.typing_timeout);
		} else {
/* remove from list and cleanup list */
			_ac_key_thunk[id] = null;
			for (i = _ac_key_thunk.length; i > 0; i--)
				if (_ac_key_thunk[i] == null)
					_ac_key_thunk.length--;
		}
	}
}

function _ac_key_check(ac,timeout) {
/* first remove any pending key check */
	for (i = _ac_key_thunk.length-1; i >= 0; i--)
		if (_ac_key_thunk[i] != null && _ac_key_thunk[i][0] == ac.obj.id) {
			clearTimeout(_ac_key_thunk[i][2]);
			_ac_key_thunk[i] = null;
		}

/* now setup a new one */
	var i = _ac_key_thunk.length;
	var handle = setTimeout("_ac_key_thunk_call("+i+")",timeout);
	_ac_key_thunk[i] = new Array(ac.obj.id,ac,handle);
}

/* helper functions to process sending timer */
var _ac_thunk = new Array();
function _ac_thunk_call(id) {
	if (_ac_thunk[id]) {
		var ac = _ac_thunk[id][1];
		ac.typing = false;
		ac.send(_ac_thunk[id][2]);
		_ac_thunk[id] = null;
		for (i = _ac_thunk.length; i > 0; i--)
			if (_ac_thunk[i] == null)
				_ac_thunk.length--;
	}
}

/* cancel a pending request */
function _ac_cancel(ac) {
	for (i = _ac_thunk.length-1; i >= 0; i--)
		if (_ac_thunk[i] != null && _ac_thunk[i][0] == ac.obj.id) {
			clearTimeout(_ac_thunk[i][3]);
			_ac_thunk[i] = null;
		}
}

function _ac_add(ac,query,timeout) {
	var i = _ac_thunk.length;
	var handle = setTimeout("_ac_thunk_call("+i+")",timeout);
	_ac_thunk[i] = new Array(ac.obj.id,ac,query,handle);
}

/* helper functions for webserver rpc processing */
var _ac_map = new Array();
function _ac_map_add(ac) {
	_ac_map[ac.obj.id] = ac;
}

/* called to initiation suggestion process */
AC.prototype.suggest = function(query) {
/* remove redundant searches */
	if (query == this.search_term)
		return;

/* cancel any existing http call */
	_ac_cancel(this);
	if (this.request && this.request.readyState != 0) {
		this.request.abort();
	}

/* check cache */
	var lc = query.toLowerCase();
	for (i = 0; i < this.cache.length; i++)
		if (this.cache[i][0] == lc) {
			var results = this.cache[i][1];
			this.search_term = query;
			this.update_popup(results);
			return;
		}

/* send call to server */
	this.typing = true;
	this.send(query);
}

/* called to send message to a server */
AC.prototype.send = function(query) {
/* check throttle timer */
	if (this.typing) {
		_ac_add(this,query,this.sending_timeout);
		return;
	}

/* initiate new call */
	this.search_term = query;
	if (this.iframe == null) {
		this.request = this.XMLHttpRequest();
		if (this.request == null) {
			var iframe = document.createElement('IFRAME');
			iframe.src = this.url+'?view=search&page=ac&i=1&id='+encodeURIComponent(this.obj.id)+'&t='+encodeURIComponent(this.type)+'&s='+encodeURIComponent(query);
/* opera 7.54 doesn't like iframe styles */
			iframe.style.width = '0px';
			iframe.style.height = '0px';
			this.iframe = this.obj.appendChild(iframe);
		 	this.obj.focus();
		} else {
/* send XmlHttpRequest */
			var AC = this;
			this.request.onreadystatechange = function() {
				if (AC.request.readyState == 4) {
					try {
						if (AC.request.status != 200 || AC.request.responseText.charAt(0) == '<') {
							/* some error */
						} else {
							eval(AC.request.responseText);
						}
					} catch (e) {}
				}
			}
			this.request.open("GET", this.url+"?view=search&page=ac&id="+encodeURIComponent(this.obj.id)+"&t="+encodeURIComponent(this.type)+"&s="+encodeURIComponent(query));
			this.request.send(null);
		}
	} else {
/* re-submit iframe */
		this.iframe.src = this.url+'?view=search&page=ac&i=1&id='+encodeURIComponent(this.obj.id)+'&t='+encodeURIComponent(this.type)+'&s='+encodeURIComponent(query);
		this.obj.focus();
	}
}

/* called with array of search results */
AC.prototype.update_popup = function(results) {
	if (this.search_term != null && results != null && results.length > 0) {
/* remove currently listed options */
		while (this.div.hasChildNodes())
			this.div.removeChild(this.div.firstChild);

/* default to first result when adding characters */
		if (this.previous_term == null || this.search_term.length >= this.previous_term.length) {
			this.selected_option = 0;
		} else {
/* remove selection when deleteing */
			this.selected_option = null;
		}
		this.previous_term = this.search_term;

		for (i = 0; i < results.length; i++) {
			var div = document.createElement('DIV');
			div.divid = results[i][2];
			div.AC = this;
			if (this.selected_option == div.divid)
				div.className = 'ac_highlight '+ results[i][4];
			else
				div.className = 'ac_normal '+ results[i][4];
			div.name = results[i][0];
			div.value = results[i][1];
			div.innerHTML = results[i][3];
			div.onmousedown = function() { this.AC.onselected(); }
			div.onmouseover = function() {
				if (this.AC.selected_option != null)
				{
					Element.removeClassName(this.AC.div.childNodes[this.AC.selected_option],'ac_highlight');
					Element.addClassName(this.AC.div.childNodes[this.AC.selected_option],'ac_normal');
				}
					//this.AC.div.childNodes[this.AC.selected_option].className = 'ac_normal ' + results[i][4];
				this.AC.selected_option = this.divid;
				this.AC.cabbage = this.AC.selected_option;
				//this.className = 'ac_highlight ' + results[i][4];
				Element.removeClassName(this,'ac_normal');
				Element.addClassName(this,'ac_highlight');
			}
			div.onmouseout = function() {
				Element.removeClassName(this,'ac_highlight');
				Element.addClassName(this,'ac_normal');
			}
			this.div.appendChild(div);
		}
		this.div.style.visibility = 'visible';

/* complete text box with selected text */

		if (this.selected_option == 0 &&
			(this.obj.createTextRange || this.obj.setSelectionRange) &&
			this.obj.value != results[0][1] &&
			results[0][1].substring(0,this.search_term.length).toLowerCase() == this.search_term.toLowerCase())
		{
			this.obj.value = results[0][1];
			if (this.obj.createTextRange) {
				var range = this.obj.createTextRange();
				range.moveStart('character',this.search_term.length);
				range.select();
			} else {
//				var range = document.createRange();
//				range.setStart(this.obj,this.search_term.length);
				this.obj.setSelectionRange(this.search_term.length,this.obj.value.length);
			}
		}
	} else {
		this.close_popup();
	}

/* update cache */
	var found = false;
	var lc = this.search_term.toLowerCase();
	for (i = 0; i < this.cache.length; i++)
		if (this.cache[i][0] == lc) {
			found = true;
			break;
		}

	if (!found) {
		this.cache[this.cache.length] = new Array(lc, results);
	}
}

/* update auto-complete input element with selected option */
AC.prototype.update_input = function() {
	/* this.obj.value = this.div.childNodes[this.selected_option].name; */
	this.obj.value = this.div.childNodes[this.selected_option].value;
}

/* when option is clicked with mouse, or entered with keyboard */
AC.prototype.onselected = function() {
	if (this.selected_option == null)
		if (this.cabbage == null)
			return;
		else
			this.selected_option = this.cabbage;	/* opera funky */

	this.update_input();

/* hide popup */
	this.close_popup();
/* submit form */
	if (this.submit_callback)
		this.submit_callback();
}

/* capture up & down actions to prevent moving cursor left or right */
/* input.onkeypress() */
AC.prototype.onkeypress = function(e) {
	if (!e) e = window.event;
	var c = e.keyCode;
	if (c == 0) c = e.charCode;
	switch (c) {
	case 38:	/* up */
	case 40:	/* down */
		e.returnValue = false;
		if (e.preventDefault) e.preventDefault();
		break;

	/* select highlighted option (moved from keyup) */
	case 13:	/* enter */
		this.AC.onselected();
		e.returnValue = false;
		if (e.preventDefault) e.preventDefault();
		break;

	default: break;
	}
}

/* move cursor on down to allow repeating */
/* input.onkeydown() */
AC.prototype.onkeydown = function(e) {
	if (!e) e = window.event;
	var c = e.keyCode;
	if (c == 0) c = e.charCode;
	var i = this.AC.selected_option == null ? -1 : this.AC.selected_option;
	switch (c) {
	case 38:	/* up */
		i--;
		e.returnValue = false;
		if (e.preventDefault) e.preventDefault();
		break;

	case 40:	/* down */
		i++;
		e.returnValue = false;
		if (e.preventDefault) e.preventDefault();
		break;

	default:
		_ac_key_check(this.AC,this.AC.typing_timeout);
		break;
	}

	if (c == 38 || c == 40) {
		var length = this.AC.div.childNodes.length;
		if (i < 0) i = 0;
		if (i >= length) i = length-1;
		if (i != this.AC.selected_option) {
			for (j = 0; j < length; j++) {
				if (j == i) {
					this.AC.obj.value = this.AC.div.childNodes[j].value;
					this.AC.selected_option = this.AC.div.childNodes[j].divid;
					//this.AC.div.childNodes[j].className = 'ac_highlight';
					Element.removeClassName(this.AC.div.childNodes[j],'ac_normal');
					Element.addClassName(this.AC.div.childNodes[j],'ac_highlight');
				} else {
					//this.AC.div.childNodes[j].className = 'ac_normal';
					Element.removeClassName(this.AC.div.childNodes[j],'ac_highlight');
					Element.addClassName(this.AC.div.childNodes[j],'ac_normal');
				}
			}

/* update search term */
			this.AC.search_term = this.AC.div.childNodes[this.AC.selected_option].value;

/* popup if hidden */
			if (this.AC.div.style.visibility == 'hidden') {
				this.AC.suggest (this.AC.searched_term);
			}
		}
	}
}

/* input.onkeyup() */
AC.prototype.onkeyup = function(e) {
	if (!e) e = window.event;
	var c = e.keyCode;
	if (c == 0) c = e.charCode;
	switch (c) {
/* prevent strange selections at top of option list */
	case 38:	/* up */
	case 40:	/* down */
		e.returnValue = false;
		if (e.preventDefault) e.preventDefault();
		break;

/* hide popup window */
	case 27:	/* escape */
		this.AC.close_popup();
		e.returnValue = false;
		if (e.preventDefault) e.preventDefault();
		break;

/* get new suggestion for new data */
	default:

/* for latin this is ok:
		if (this.value.length > 0) {
			this.AC.searched_term = this.value;
			this.AC.suggest(this.value);
		} else {
			_ac_cancel(this.AC);
			this.AC.close_popup();
		}
*/
		break;
	}
}

/* iframe or XmlHttpRequest() callback */
function _ac_rpc() {
	var id = arguments[0];
	if (_ac_map[id]) {
/* we cannot shift() arguments as it is an object :( */
		_ac_map[id].process_reply.apply(_ac_map[id],arguments);
	}
}

/* parse rpc results into html for the popup */
AC.prototype.process_reply = function() {
	var results = new Array();
	var c = 0;
	var re = new RegExp('('+this.searched_term+')', "gi");
	var nt = '<font color="red"><b>$1</b></font>';
	for (i = 1; i < arguments.length; i += 3) {
		var name = this.highlight ? arguments[i+1].replace(re, nt) : arguments[i+1];
		var value = this.highlight ? arguments[i].replace(re, nt) : arguments[i];
		var html = "<span class='d'>"+name+"</span><span class='a'>"+value+"</span>";
		results[c] = new Array(arguments[i+1], arguments[i], c, html, arguments[i+2]);
		c++;
	}

	this.update_popup(results);
}

function makeResizable(ta)
{
		wrapper = document.createElement('DIV');
		wrapper.className = 'resizerWrapper';
		ta.parentNode.replaceChild(wrapper, ta);
		wrapper.appendChild(ta);

		bigger = document.createElement('A');
		bigger.className = 'resizeBigger';
		bigger.href = 'javascript:void();';

		smaller = document.createElement('A');
		smaller.className = 'resizeSmaller';
		smaller.href='javascript:void();';

		biggerFont = document.createElement('A');
		biggerFont.className = 'resizeBiggerFont';
		biggerFont.href = 'javascript:void();';

		smallerFont = document.createElement('A');
		smallerFont.className = 'resizeSmallerFont';
		smallerFont.href='javascript:void();';

		smallerSpan = document.createElement('SPAN');
		smallerSpan.appendChild(document.createTextNode('smaller'));

		biggerSpan = document.createElement('SPAN');
		biggerSpan.appendChild(document.createTextNode('bigger'));

		smallerFontSpan = document.createElement('SPAN');
		smallerFontSpan.appendChild(document.createTextNode('smaller font'));

		biggerFontSpan = document.createElement('SPAN');
		biggerFontSpan.appendChild(document.createTextNode('bigger font'));

		bigger.appendChild(biggerSpan);
		smaller.appendChild(smallerSpan);
		biggerFont.appendChild(biggerFontSpan);
		smallerFont.appendChild(smallerFontSpan);

		bigger.resizer = ta;
		smaller.resizer = ta;
		biggerFont.resizer = ta;
		smallerFont.resizer = ta;

		bigger.onclick = function()
		{
			if (this.resizer.style.height == '')
				this.resizer.style.height = this.resizer.clientHeight+'px';
			this.resizer.style.height = (parseInt(this.resizer.style.height) + 30) + "px";
			return false;
		}

		smaller.onclick = function()
		{
			if (this.resizer.style.height == '')
				this.resizer.style.height = this.resizer.clientHeight+'px';

			if ((parseInt(this.resizer.style.height) - 30) > 30)
				this.resizer.style.height = (parseInt(this.resizer.style.height) - 30) + "px";
			return false;
		}

		biggerFont.onclick = function()
		{
			if (this.resizer.style.fontSize == '')
				this.resizer.style.fontSize = '1em';

			this.resizer.style.fontSize = (parseFloat(this.resizer.style.fontSize) + 0.1) + "em";

			return false;
		}

		smallerFont.onclick = function()
		{
			if (this.resizer.style.fontSize == '')
				this.resizer.style.fontSize = '1em';

			if ((parseFloat(this.resizer.style.fontSize) - 0.1) > 0.5)
				this.resizer.style.fontSize = (parseFloat(this.resizer.style.fontSize) - 0.1) + "em";

			return false;
		}

		wrapper.appendChild(bigger);
		wrapper.appendChild(smaller);
		wrapper.appendChild(biggerFont);
		wrapper.appendChild(smallerFont);
}


/**************************************
* Jonas Raoni Soares Silva
* http://www.joninhas.ath.cx
**************************************/

String.prototype.pad = function(l, s, t){ //v1.0
    return s || (s = " "), (l -= this.length) > 0 ? (s = new Array(Math.ceil(l / s.length)
        + 1).join(s)).substr(0, t = !t ? l : t == 1 ? 0 : Math.ceil(l / 2))
        + this + s.substr(0, l - t) : this;
};

// CSS Browser Selector   v0.1.7
// Documentation:         http://rafael.adm.br/css_browser_selector
// License:               http://creativecommons.org/licenses/by/2.5/
// Author:                Rafael Lima (http://rafael.adm.br)
// Contributors:          http://rafael.adm.br/css_browser_selector#contributors
var css_browser_selector = function() {
	var ua = navigator.userAgent.toLowerCase();
	var h = document.getElementsByTagName('html')[0];
	var c = h.className;

	if(ua.indexOf('msie') != -1 && !(ua.indexOf('opera') != -1) && (ua.indexOf('webtv') == -1) ) h.className='ie'+' ie'+ua.charAt(ua.indexOf('msie')+5)+' '+c;
	else if(ua.indexOf('gecko/') != -1) h.className=('gecko '+c);
	else if(ua.indexOf('opera') != -1) h.className=('opera '+c);
	else if(ua.indexOf('konqueror') != -1) h.className=('konqueror '+c);
	else if(ua.indexOf('applewebkit/') != - 1) h.className=('webkit safari '+c);
	else if(ua.indexOf('mozilla/') != -1) h.className=('gecko '+c);
}.apply(this);


//Sidebar
function toggle_sidebar(){
  var myClass=document.getElementById('content').className;
	if (myClass=='expanded')
	{
		new Effect.Appear('sidebar');
		toggle_content();
		document.cookie = "sidebar=true;path=/";
	}
	else
	{
		new Effect.Fade('sidebar',{onFinish:toggle_content()});
		document.cookie = "sidebar=false;path=/";
	}
}

var toggle_content=function(){
  var myClass=document.getElementById('content');
	myClass.className = (myClass.className=='expanded') ? 'collapsed' : 'expanded';
}

//Simulator
var simulator = Class.create();
simulator.prototype = {
	initialize:function(s,o,a)
	{
		this.a = a ? a : document.location;
		this.o = $(o);
		this.s = $(s);
		this.iA = $$('#'+s+' input');
		this.iA.each(function(el){
				this.format_js(el);
				el.onchange = this.change.bindAsEventListener(this);
				el.onkeyup = this.kchange.bindAsEventListener(this);
				if(el.className=='throttle')
					this.addControls(el);
			}.bind(this));
	},
	format_js:function(el)
	{
		if ($(el).value.match(/^[0-9.,]*$/g))
		{
			$(el).value = $(el).value.replace(/[,]/g,'.');
			$(el).value = $(el).value.replace(/[^\d.]+/g,'');
		}
	},
	kchange:function(el)
	{
		switch(el.keyCode)
		{
			case Event.KEY_LEFT:
			case Event.KEY_RIGHT:
			break;

			default:
			el = Event.element(el);
			this.format_js(el);
			this.retrieveResult();
		}
	},
	change:function(el)
	{
		el = Event.element(el);
		//this.format_js(el);
		this.retrieveResult();
	},
	addControls:function(el){
		var ec = document.createElement('div');
		ec.className='ctrl';
		ec.title = el.id;
		var eb = document.createElement('div');
		eb.className='inc';
		eb.onclick = this.incValue.bindAsEventListener(this);
		ec.appendChild(eb);
		var eb = document.createElement('div');
		eb.className='dec';
		eb.onclick = this.decValue.bindAsEventListener(this);
		ec.appendChild(eb);
		el.parentNode.insertBefore(ec,el);
	},
	incValue:function(evt){
		var el = $(Event.element(evt).parentNode.title)
		var val = parseFloat(el.value);
		if(el.alt)
		{
			el.value = (val + 0.1).toPrecision(el.alt);
		}
		else
		{
			el.value = (val + 1).toFixed(2);
		}
		this.retrieveResult();
	},
	decValue:function(evt){
		var el = $(Event.element(evt).parentNode.title)
		if(el.value > 0)
		{
			var val = parseFloat(el.value);
			if(el.alt)
			{
				el.value = (val - 0.1).toPrecision(el.alt);
			}
			else
			{
				el.value = (val - 1).toFixed(2);
			}
		}
		this.retrieveResult();
	},
	retrieveResult:function(c)
	{
		var PD = 'simulator=' + this.s.id;
		this.iA.each(function(el){
			PD += '&' + $(el).name + '=' + $F(el)
		}.bind(this));
		new Ajax.Updater(this.o,this.a,
				     				{
				     					method:'post',
				     					parameters: PD,
				     					evalScripts: true,
				     					onFailure: function()
				     					{
				     						alert('ajax failed');
				     					}
				     				});
	}
};

//Context Help
var contexthelp = Class.create();
contexthelp.prototype = {
	initialize:function(el){
		this.el = $(el);
		if(this.el.innerHTML)
		{
			this.helpHTML = this.el.innerHTML;
			this.el.innerHTML = '[?]';
		  this.oldposition = this.el.style.position;
			this.oldwidth = this.el.style.width;
			this.el.onmouseover = this.show.bindAsEventListener(this);
			this.el.onmouseout = this.hide.bindAsEventListener(this);
		}
	},
	show:function(evt){
		Element.addClassName(this.el,'help_active');
		this.el.innerHTML = this.helpHTML;
	},
	hide:function(evt){
		Element.removeClassName(this.el,'help_active');
		this.el.innerHTML = '[?]';
	}
}

// HTTP.Cookies - Burak Gürsoy <burak[at]cpan[dot]org>
if (!HTTP) var HTTP = {}; // create base class if undefined

HTTP.Cookies = function () { // HTTP.Cookies constructor
   this.JAR = ''; // data cache
}

HTTP.Cookies.VERSION = '1.01';

HTTP.Cookies.Date = function () { // expire time calculation class
   this.format = {
   's' : 1,
   'm' : 60,
   'h' : 60 * 60,
   'd' : 60 * 60 * 24,
   'M' : 60 * 60 * 24 * 30,
   'y' : 60 * 60 * 24 * 365
   };
}

HTTP.Cookies.Date.prototype.parse = function (x) {
   if(!x || x == 'now') return 0;
   var date = x.match(/^(.+?)(\w)$/i);
   var of = 0;
   return (this.is_num(date[1]) && (of = this.is_date(date[1],date[2]))) ? of : 0;
}

HTTP.Cookies.Date.prototype.is_date = function (num, x) {
   if (!x || x.length != 1) return 0;
   var ar = [];
   return (ar = x.match(/^(s|m|h|d|w|M|y)$/) ) ? num * 1000 * this.format[ar[0]] : 0;
}

HTTP.Cookies.Date.prototype.is_num = function (x) {
   if (x.length == 0) return;
   var ok = 1;
   for (var i = 0; i < x.length; i++) {
      if ("0123456789.-+".indexOf(x.charAt(i)) == -1) {
         ok--;
         break;
      }
   }
   return ok;
}

HTTP.Cookies.prototype.date = new HTTP.Cookies.Date; // date object instance

// Get the value of the named cookie. Usage: password = cookie.read('password');
HTTP.Cookies.prototype.read = function (name) {
   var value  = '';
   if(!this.JAR) {
		this.JAR = {};
      var array  = document.cookie.split(';');
      for (var x = 0; x < array.length; x++) {
         var pair = array[x].split('=');
         if(pair[0].substring (0,1) == ' ') pair[0] = pair[0].substring(1, pair[0].length);
         if(pair[0] == name) {
            value = pair[1];
         }
         this.JAR[pair[0]] = pair[1];
      }
   } else {
      for(var cookie in this.JAR) {
         if(cookie == name) {
            value = this.JAR[cookie];
         }
	   }
   }
   return value ? unescape(value) : '';
}

// Create a new cookie or overwrite existing. Usage: cookie.write('password', 'secret', '1m');
HTTP.Cookies.prototype.write = function (name, value, expires, path, domain, secure) {
   var extra = '';
   if (!expires) expires = '';
   if (expires == '_epoch') {
      expires = new Date(0);
   } else if (expires != -1) {
      var Now  = new Date;
      Now.setTime(Now.getTime() + this.date.parse(expires));
      expires = Now.toGMTString();
   }
   if(expires) extra += "; expires=" + expires;
   if(path   ) extra += "; path="    + path; else extra += "; path=/";
   if(domain ) extra += "; domain="  + domain;
   if(secure ) extra += "; secure="  + secure;
   document.cookie = name + "=" + escape(value) + extra;
}

// Delete the named cookie. Usage: cookie.remove('password');
HTTP.Cookies.prototype.remove = function (name, path, domain, secure) {
   this.write(name, '', '_epoch', path, domain, secure);
}
var cookie = new HTTP.Cookies;

var ticker = Class.create();
ticker.prototype = {
	initialize:function(el,els,frequency)
	{
		this.el = $(el);
		this.els = els;
		this.pointer = 0;
		this.f = frequency;
		this.fade();
	},
	fade:function()
	{

		if (this.els.length <= ((this.pointer++)+1))
		this.pointer=0;
		//Element.hide(this.el);
		window.setTimeout(this.update.bind(this),150);
	},
	update:function()
	{
		this.el.innerHTML = this.els[this.pointer];
		//Element.show(this.el);
		window.setTimeout(this.fade.bind(this),(this.f * 1000));
	}
};


	function screencheck(ct)
	{
		if (ct=='h')
		{
			var content = Number($('content').offsetWidth);
			if($('check_t_size').offsetWidth > content)
				content = $('check_t_size').offsetWidth;
			var new_width = 30 + content + Number($('sidebar').offsetWidth);
			if (new_width > Number($('container').offsetWidth))
			{
				$('main').style.width = new_width+'px';
				$('container').style.width = new_width+'px';
			}
		}
		else if ($('start_side'))
		{
			var new_height = 10+ Number($('start_side').offsetHeight);
			if (new_height > Number($('content').offsetHeight))
			{
				$('content').style.height = new_height+'px';
			}
		}
	}

  // php-like ucwords for javascript strings
  String.prototype.ucwords = function(){
     return this.toLowerCase().replace(/\S+/g,function(s){
          return s.charAt(0).toUpperCase() + s.substr(1);
     })
  }
