/* SkinGzip V 1.0.3770.17931, PackageDate: 09.09.2010 01:32:03 */

function Boot()
{
	var divs = document.getElementsByTagName("div");
	var div;
	for(var i=0; (div = divs[i]); i++)
		if(div.className)
			if(div.className.charAt(0) == "$")
				InitControl(div);
}
function InitControl(div)
{
	if(div.className == "$DataSheet")
		InitDataSheet(div);
}

Browser = new Object();
Browser.UA = navigator.userAgent;
Browser.AV = navigator.appVersion;
Browser.mac = Browser.AV.indexOf("Macintosh") == -1 ? false : true; 
Browser.win = Browser.AV.indexOf("Windows") == -1 ? false : true; 
Browser.opera = Browser.UA.indexOf("Opera") == -1 ? false : true; 
Browser.khtml = ((Browser.AV.indexOf("Konqueror") >= 0)||(Browser.AV.indexOf("Safari") >= 0)) ? true : false; 
Browser.safari = (Browser.AV.indexOf("Safari") >= 0) ? true : false; 
Browser.mozilla = Browser.moz = ((Browser.UA.indexOf("Gecko") >= 0)&&(!Browser.khtml)) ? true : false; 
Browser.ie = ((document.all)&&(!Browser.opera)) ? true : false;
Browser.ie50 = Browser.ie && Browser.AV.indexOf("MSIE 5.0")>=0;
Browser.ie55 = Browser.ie && Browser.AV.indexOf("MSIE 5.5")>=0;
Browser.ie60 = Browser.ie && Browser.AV.indexOf("MSIE 6.0")>=0;

var Events = new Object();
Events.AddHandler = function(obj, type, fn)
{
	if(obj.tagName && obj.tagName.toLowerCase() == "a")
		obj.href = "javascript:void(0)";
	if(obj.addEventListener)
	{
		obj.addEventListener(type, fn, false);
		return true;
	}
	if(obj.attachEvent)
		return obj.attachEvent("on"+type, fn);
	return false;
}
Events.GetSender = function(e)
{
	if(!e)
		var e = window.event;
	if(e.srcElement)
		return e.srcElement;
	else if(e.currentTarget)
		return e.currentTarget;
	else
		return null;
}
//----
var $$Keys = {BackSpace:8,Tab:9,Enter:13,Esc:27,Space:32,PgUp:33,PgDown:34,End:35,Home:36,Left:37,Up:38,Right:39,Down:40,Del:46,
	F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123}
var a = [];
for(k in $$Keys)
	a.push({k:k, v:$$Keys[k]});
for(k in a)
	$$Keys[a[k].v] = a[k].k;

/**************************************************
*  DataSheet
***************************************************/
var EditedDataSheet;
function InitDataSheet(div)
{
	var table = div.getElementsByTagName("table")[0];
	var initializer = $(table.id + "_changes")
	var changes = initializer.value;
	if(changes.length == 0)
		return;
	eval("table.Changes=" + changes);
	initializer.value = GetDataSheetChangeLog(table);
}
function EditDataSheetCell(cell)
{
	// {className:[classname], width: [width offset], height: [height offset]}
	if(cell.edited)
		return false;
	EndEditDataSheetCell();
	var span = cell.childNodes[0];
	if(span.nodeName.toLowerCase() == "span")
	{
		var table = GetAncestor(cell, "table");
		EditedDataSheet = table;
		var config = GetConfig(table);
		cell.edited = true;
		table.editedCell = cell;
		var oldValue = span.innerHTML;
		var align = "left";
		cell.innerHTML = '<input type="text" autocomplete="off" class="' + config.className + '" style="text-align: ' + align + ';width: ' + (cell.clientWidth+config.width) + '; height: ' + (cell.clientHeight+config.height) + '" value="' + oldValue + '" />';
		cell.oldValue = oldValue;
		var editor = cell.childNodes[0];
		editor.focus();
		editor.select();
		if(Browser.ie)
		{
			editor.onkeydown = _editor_onKey;
		}
		else if(Browser.mozilla)
		{
			editor.selectionStart = 0;
			editor.selectionEnd = editor.textLength;
			editor.onkeypress = _editor_onKey;
		}
	}
}
function IsEditable(cell)
{
	return cell.childNodes[0].nodeName.toLowerCase() == "span";
}
function EndEditDataSheetCell()
{
	if(EditedDataSheet == null)
		return;
	var table = EditedDataSheet;
	var cell = table.editedCell;
	if(cell == null)
		return;
	cell.edited = false;
	table.editedCell = null;
	EditedDataSheet = null;
	var newValue = cell.childNodes[0].value;
	s = "<span title='" + newValue + "'>" + newValue + "</span>";
	cell.innerHTML = s;
	if(cell.oldValue == newValue)
		return;
	var logControl = $(table.id + "_changes");
	if(table.Changes == null)
		table.Changes = new Array();
	//-- log
	var row = cell.parentNode;
	var rows = row.parentNode.rows.length;
	var cells = row.cells.length;
	var cellIndex = cell.cellIndex;
	var rowIndex = row.sectionRowIndex;
	var index = rowIndex * cells + cellIndex;
	table.Changes[index] = newValue;
	logControl.value = GetDataSheetChangeLog(table);
}
function GetDataSheetChangeLog(table)
{
	var s = v = "";
	for(var key in table.Changes)
	{
		v = table.Changes[key].replace(/&/g, "&amp;").replace(/\</g, "&lt;").replace(/\>/g, "&gt;");
		s += '<c i="'+key+'">'+v+'</c>';
	}
	return s;
}
_editor_onKey = function(e)
{
	var hNode = Events.GetSender(e);
	e = (e||event);

	var cancel = validate = ifFullSelect = reset = endEdit = deselect = false;
	var dx = dy = 0;
	switch(e.keyCode)
	{
		case $$Keys.Tab:   dx=e.shiftKey?-1:1; cancel=true; break;
		case $$Keys.Enter: validate=true;cancel=true; endEdit=true; break;
		case $$Keys.Up:    dy=-1; break;
		case $$Keys.Down:  dy= 1; break;
		case $$Keys.Left:  dx=-1; ifFullSelect=true; break;
		case $$Keys.Right: dx= 1; ifFullSelect=true; break;
		case $$Keys.F2:    deselect=true; break;
		default: return;
	}

	//-- check fullselect
	var fullSelect = cursorAtStart = cursorAtEnd = false;
	if(ifFullSelect)
	{
		if(Browser.ie)
		{
			var r = document.selection.createRange();
			
			fullSelect = hNode.value == r.text;
			if(r.text == "")
			{
				cursorAtStart = !r.moveStart("character", -1);
				cursorAtEnd = !r.moveEnd("character", 1);
			}
		}
		else if(Browser.mozilla)
		{
			fullSelect = hNode.selectionEnd - hNode.selectionStart == hNode.textLength;
			cursorAtStart = hNode.selectionStart == hNode.selectionEnd && hNode.selectionStart == 0;
			cursorAtEnd = hNode.selectionStart == hNode.selectionEnd && hNode.selectionEnd == hNode.textLength;
		}
		if(!fullSelect)
			if(!((dx > 0 && cursorAtEnd) || (dx < 0 && cursorAtStart)))
				dx = 0;
	}

	//-- check validation
	validate = validate || dx || dy;

	//-- execution: validate, dx, dy
	if(validate)
	{
		//TODO: validation
		var cell = hNode.parentNode;
		var row = cell.parentNode;
		var rows = row.parentNode.rows.length;
		var cells = row.cells.length
		var cellIndex = cell.cellIndex;
		var rowIndex = row.sectionRowIndex;

		if(endEdit)
		{
			EndEditDataSheetCell();
		}
		else
		{
			do
			{	
				cell = null;
				cellIndex += dx;
				rowIndex += dy;
				if(cellIndex < 0)
				{
					cellIndex = cells-1;
					rowIndex--;
				}
				if(cellIndex >= cells)
				{
					cellIndex = 0;
					rowIndex++;
				}
				if(rowIndex >= 0 && rowIndex < rows)
				{
					row = row.parentNode.rows[rowIndex];
					cell = row.cells[cellIndex];
					if(IsEditable(cell))
						break;
				}
			}while(cell);
			if(cell)
				EditDataSheetCell(cell);
		}
	}
	if(deselect)
	{
		//TODO: szelekcio nincs + textbox vegere tenni a kurzort
	}
	if(cancel)
	{
		if(Browser.ie)
			event.returnValue = false;
		else if(Browser.mozilla)
			e.preventDefault();
	}

	return !cancel;
}
function GetConfig(hNode)
{
	var id = hNode.id + "_config";
	var src = $(id).value;
	var x;
	eval("x="+src);
	return x;
}
function GetAncestor(hNode, name)
{
	if(!hNode || !hNode.nodeName)
		return null;
	if(hNode.nodeName.toLowerCase() == name)
		return hNode;
	return GetAncestor(hNode.parentNode, name);
}
function $(id)
{
	return document.getElementById(id);
}

Events.AddHandler(window, "load", Boot);

/**************************************************
*  Postolshoz tartoz fggvnyek
***************************************************/
var bEnableSubmit = true;
function Submit(form)
{
	// Edit mdban nem submitoldnak a linkek ezrt az edit pageben definilva van egy EditMode vltoz.
	
	var bEditMode;
	try
	{
		bEditMode = EditMode;
	}
	catch(e)
	{
		bEditMode = false;
	}
	
	if(!document.all)
	{
		window.onunload = null;
	}
	else
	{
		if(!bEnableSubmit)
		{
			return false;
		}
		bEnableSubmit = false;
	}
	for(var i=0; i<document.forms.length; i++)
	{	
		if(document.forms[i].id != form.id)
		{
			
			if (document.createElement)
			{
			
				var x;
				if (document.all)
				{
					try
					{
						x=document.createElement("<input type=hidden name='__SNPEPortletState_" + document.forms[i].id + "'>");
						x.value = document.forms[i].all["__SNPEPortletState_" + document.forms[i].id].value;
						form.appendChild(x);						
					}
					catch(e)
					{
					}
				}
				else
				{
					try
					{
						x=document.createElement("INPUT"); 
						x.type='hidden'; 
						x.name='__SNPEPortletState_' + document.forms[i].id;
						x.value=document.forms[i].elements["__SNPEPortletState_" + document.forms[i].id].value;
						form.appendChild(x);
					}
					catch(e)
					{}
				}
			}
		}
	}
	var y;
	
	try
	{
		if (document.all)
				{
				    
					try
					{
	                    y=document.createElement("<input type='hidden' name='__SNPEPortletPosition'>");
	                    y.value = y.pageYOffset || y.pageYOffset ||  document.documentElement.scrollTop || document.body.scrollTop;
		                form.appendChild(y);
	                   					
					}
					catch(e)
					{
					    
					}
				}
				else
				{
					
					try
					{
		                y = document.createElement("INPUT"); 
		                y.type='hidden'; 
		                y.name='__SNPEPortletPosition';
                	
		                y.value = y.pageYOffset || y.pageYOffset ||  document.documentElement.scrollTop || document.body.scrollTop;
		                form.appendChild(y);
					}
					catch(e)
					{}
				}

	}
	catch(e)
	{}
	
	return true;
}

function SubmitLink(formname, linkname)
{
	// Edit mdban nem submitoldnak a linkek ezrt az edit pageben definilva van egy EditMode vltoz.
	
	
	var bEditMode;
	try
	{
		bEditMode = EditMode;
	}
	catch(e)
	{
		bEditMode = false;
	}
		
	
	if (!bEditMode)
	{
		var form = document.forms[formname];
		var x;
		if(bEnableSubmit)
		{
			if (document.all)
			{
				x = document.createElement("<input type=hidden name='__SNPEPortletSubmitLink'>");
				x.value = form.id + "_" + linkname;
			}
			else
			{
				x=document.createElement("INPUT"); 
				x.type='hidden'; 
				x.name='__SNPEPortletSubmitLink';
				x.value = form.id + "_" + linkname;
			}
			form.appendChild(x);
			Submit(form);
			bEnableSubmit = false;
		}
		form.submit();	
	}
}
var _yPos;
function ScrollTo()
{
	{
		window.scrollTo(0, _yPos);
		
		InitPage();
	}
}
function SetScrollPos(y)
{
	_yPos = y;
	if (Browser.ie) document.onreadystatechange = ScrollTo;
	else document.addEventListener("DOMContentLoaded", ScrollTo, false);
}
/**************************************************
*  Postolshoz tartoz fggvnyek vge
***************************************************/

/**************************************************
*  Modlis ablak nyitshoz tartoz fggvnyek 
***************************************************/
var _content, _placeholderid, _title, _width, _height;
function openModalWindow()
{
	
	if(document.readyState == 'complete' || !document.all)
	{
		
		var form = document.getElementById(_placeholderid);
		var vRet = window.showModalDialog("ModalWindow.aspx?contentname=" + _content + "&placeholderid=" + _placeholderid,_title, "resizable:yes;scroll:no;dialogHeight:" + _height + "px;dialogWidth:" + _width + "px;");
		
		if(vRet != null)
		{
			form.all["__SNPEPortletState_" + _placeholderid].value = vRet;
		}
		else
		{	
			var cancelElem = document.createElement("<input type=hidden name='__SNPEPortletModalWindowCanceled'>");
			cancelElem.value = 'true';
			form.appendChild(cancelElem);
		}
		var x = document.createElement("<input type=hidden name='__SNPEPortletModalWindowClosed'>");
		x.value = 'true';
		form.appendChild(x);
		Submit(form);
		form.submit();
	}
}
function OpenModalWindow(content, placeholderid, title, width, height)
{

	if(document.all)
	{
		_content = content;
		_placeholderid = placeholderid;
		_width = width;
		_title = title;
		_height = height;
		document.onreadystatechange = openModalWindow;
	}
	else
	{
		var vRet = window.open("ModalWindow.aspx?contentname=" + content + "&placeholderid=" + placeholderid,title, "chrome,all,dialog=yes,resizable=yes,modal");
		
	}
}

function MozillaWinClose(placeholderid, notCancel)
{
	var vRet;
	try
	{
		var fModal = document.getElementById(placeholderid);
		vRet = fModal.elements["__SNPEPortletState_" + placeholderid].value;
	}
	catch(e)
	{
	}
	var form = window.opener.document.getElementById(placeholderid);
	if(notCancel)
	{
		form.elements["__SNPEPortletState_" + placeholderid].value = vRet;
	}
	else
	{	
		var cancelElem = window.opener.document.createElement("INPUT"); 
		cancelElem.type='hidden'; 
		cancelElem.name='__SNPEPortletModalWindowCanceled';
		cancelElem.value = 'true';
		form.appendChild(cancelElem);
	}
	
	
	var x = window.opener.document.createElement("INPUT"); 
	x.type='hidden'; 
	x.name='__SNPEPortletModalWindowClosed';
	x.value = 'true';
	form.appendChild(x);
	
	//Submit(form);
	for(var i=0; i<window.opener.document.forms.length; i++)
	{	
		if(window.opener.document.forms[i].id != form.id)
		{
			var x;
			try
			{
				x = window.opener.document.createElement("INPUT"); 
				x.type = 'hidden'; 
				x.name = '__SNPEPortletState_' + document.forms[i].id;
				x.value = window.opener.document.forms[i].items["__SNPEPortletState_" + window.parent.document.forms[i].id].value;
				form.appendChild(x);
			}
			catch(e)
			{}
		}
	}
	//window.document.body.onUnload = test;
	
	
	//if(!notCancel)
	window.close();
	if(window.opener != null)
	{
		window.opener.onunload = null;
	}
	//window.opener.document.forms[placeholderid].submit();
	form.submit();
}	
/**************************************************
*  Modlis ablak nyitshoz tartoz fggvnyek vge
***************************************************/
var MaxIcon = "icoMax.gif";
var MinIcon = "icoMin.gif";

function WinMinMax(tr, img)
{
	var path = ImgFullPath(img);
	if(document.all.item(tr).style.display == ''){
		document.all.item(tr).style.display = 'none';
		img.src = path + MaxIcon;
		setCookie(tr, "c");
	}else{
		document.all.item(tr).style.display = ''
		img.src = path + MinIcon;
		setCookie(tr, "o");
	}
}
function ImgFullPath(oImg){
	var path = "";
	try{
		path = "SysRes/" + oImg.getAttribute("skin") + "/ctrl/";
	}
	catch(e){
		path = "SysRes/SNPESkin/ctrl/";
	}
	return path
}
//cookies

function setCookie(name, value) 
{   var today = new Date();
	var expire = new Date();   
	expire.setTime(today.getTime() + 1000*60*60*24*365);
	document.cookie = name + "=" + escape(value)   + ((expire == null) ? "" : ("; expires=" + expire.toGMTString()));
}
function getCookie(Name) 
{   
  var search = Name + "=";
  if (document.cookie.length > 0) 
  { // if there are any cookies      
     offset = document.cookie.indexOf(search)       
     if (offset != -1) 
     { // if cookie exists          
       offset += search.length          
       // set index of beginning of value         
       end = document.cookie.indexOf(";", offset)          
       // set index of end of cookie value         
       if (end == -1)             
          end = document.cookie.length         
       return unescape(document.cookie.substring(offset, end))      
     }    
  }
}


document.onreadystatechange = InitPage;

function InitPage()
{
	if(document.readyState == 'complete')
	{
		for(var i=0; i<document.forms.length; i++)
		{	
			if (document.all)
			{
				try
				{
					x = document.forms[i].all["__snpeplaceholderid"].value ;
					var tr = document.all.item(x + "_body");
					var oImg = document.all.item(x + "_minmax");
					var path = ImgFullPath(oImg);
					if(getCookie(x + "_body") == "o")
					{
						tr.style.display = "";
						if(oImg != null)
							oImg.src = path + MinIcon;
					}
					if(getCookie(x + "_body") == "c")
					{						
						if(oImg != null)
						{
							tr.style.display = "none";
							oImg.src = path + MaxIcon;
						}
					}
					
				}
				catch(e)
				{
				}
			}
		}
	}
}
/* tree-hez kapcsolodo fuggvenyek */
function showOrHide(formid, iconPrefix, id, pid) {
	if (document.all.item(id).style.display == "") {
		document.all.item(id).style.display = "none";
		document.images(pid).src = iconPrefix + "p.gif";
		document.forms[formid].all[document.all.item(id).snpeID].value = "0";
	}else{
		document.all.item(id).style.display = "";
		document.images(pid).src = iconPrefix + "m.gif";
		document.forms[formid].all[document.all.item(id).snpeID].value = "1";
	}
}
/* tree-hez kapcsolodo fuggvenyek vege */
/*  Prototype JavaScript framework, version 1.5.0_rc1
 *  (c) 2005 Sam Stephenson <sam@conio.net>
 *
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the Prototype web site: http://prototype.conio.net/
 *
/*--------------------------------------------------------------------------*/

var Prototype = {
  Version: '1.5.0_rc1',
  ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',

  emptyFunction: function() {},
  K: function(x) {return x}
}

var Class = {
  create: function() {
    return function() {
      this.initialize.apply(this, arguments);
    }
  }
}

var Abstract = new Object();

Object.extend = function(destination, source) {
  for (var property in source) {
    destination[property] = source[property];
  }
  return destination;
}

Object.extend(Object, {
  inspect: function(object) {
    try {
      if (object == undefined) return 'undefined';
      if (object == null) return 'null';
      return object.inspect ? object.inspect() : object.toString();
    } catch (e) {
      if (e instanceof RangeError) return '...';
      throw e;
    }
  },

  keys: function(object) {
    var keys = [];
    for (var property in object)
      keys.push(property);
    return keys;
  },

  values: function(object) {
    var values = [];
    for (var property in object)
      values.push(object[property]);
    return values;
  },

  clone: function(object) {
    return Object.extend({}, object);
  }
});

Function.prototype.bind = function() {
  var __method = this, args = $A(arguments), object = args.shift();
  return function() {
    return __method.apply(object, args.concat($A(arguments)));
  }
}

Function.prototype.bindAsEventListener = function(object) {
  var __method = this, args = $A(arguments), object = args.shift();
  return function(event) {
    return __method.apply(object, [( event || window.event)].concat(args).concat($A(arguments)));
  }
}

Object.extend(Number.prototype, {
  toColorPart: function() {
    var digits = this.toString(16);
    if (this < 16) return '0' + digits;
    return digits;
  },

  succ: function() {
    return this + 1;
  },

  times: function(iterator) {
    $R(0, this, true).each(iterator);
    return this;
  }
});

var Try = {
  these: function() {
    var returnValue;

    for (var i = 0; i < arguments.length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) {}
    }

    return returnValue;
  }
}

/*--------------------------------------------------------------------------*/

var PeriodicalExecuter = Class.create();
PeriodicalExecuter.prototype = {
  initialize: function(callback, frequency) {
    this.callback = callback;
    this.frequency = frequency;
    this.currentlyExecuting = false;

    this.registerCallback();
  },

  registerCallback: function() {
    this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  stop: function() {
    if (!this.timer) return;
    clearInterval(this.timer);
    this.timer = null;
  },

  onTimerEvent: function() {
    if (!this.currentlyExecuting) {
      try {
        this.currentlyExecuting = true;
        this.callback(this);
      } finally {
        this.currentlyExecuting = false;
      }
    }
  }
}
Object.extend(String.prototype, {
  gsub: function(pattern, replacement) {
    var result = '', source = this, match;
    replacement = arguments.callee.prepareReplacement(replacement);

    while (source.length > 0) {
      if (match = source.match(pattern)) {
        result += source.slice(0, match.index);
        result += (replacement(match) || '').toString();
        source  = source.slice(match.index + match[0].length);
      } else {
        result += source, source = '';
      }
    }
    return result;
  },

  sub: function(pattern, replacement, count) {
    replacement = this.gsub.prepareReplacement(replacement);
    count = count === undefined ? 1 : count;

    return this.gsub(pattern, function(match) {
      if (--count < 0) return match[0];
      return replacement(match);
    });
  },

  scan: function(pattern, iterator) {
    this.gsub(pattern, iterator);
    return this;
  },

  truncate: function(length, truncation) {
    length = length || 30;
    truncation = truncation === undefined ? '...' : truncation;
    return this.length > length ?
      this.slice(0, length - truncation.length) + truncation : this;
  },

  strip: function() {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
  },

  stripTags: function() {
    return this.replace(/<\/?[^>]+>/gi, '');
  },

  stripScripts: function() {
    return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
  },

  extractScripts: function() {
    var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
    var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
    return (this.match(matchAll) || []).map(function(scriptTag) {
      return (scriptTag.match(matchOne) || ['', ''])[1];
    });
  },

  evalScripts: function() {
    return this.extractScripts().map(function(script) { return eval(script) });
  },

  escapeHTML: function() {
    var div = document.createElement('div');
    var text = document.createTextNode(this);
    div.appendChild(text);
    return div.innerHTML;
  },

  unescapeHTML: function() {
    var div = document.createElement('div');
    div.innerHTML = this.stripTags();
    return div.childNodes[0] ? div.childNodes[0].nodeValue : '';
  },

  toQueryParams: function() {
    var pairs = this.match(/^\??(.*)$/)[1].split('&');
    return pairs.inject({}, function(params, pairString) {
      var pair  = pairString.split('=');
      var value = pair[1] ? decodeURIComponent(pair[1]) : undefined;
      params[decodeURIComponent(pair[0])] = value;
      return params;
    });
  },

  toArray: function() {
    return this.split('');
  },

  camelize: function() {
    var oStringList = this.split('-');
    if (oStringList.length == 1) return oStringList[0];

    var camelizedString = this.indexOf('-') == 0
      ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1)
      : oStringList[0];

    for (var i = 1, len = oStringList.length; i < len; i++) {
      var s = oStringList[i];
      camelizedString += s.charAt(0).toUpperCase() + s.substring(1);
    }

    return camelizedString;
  },

  inspect: function(useDoubleQuotes) {
    var escapedString = this.replace(/\\/g, '\\\\');
    if (useDoubleQuotes)
      return '"' + escapedString.replace(/"/g, '\\"') + '"';
    else
      return "'" + escapedString.replace(/'/g, '\\\'') + "'";
  }
});

String.prototype.gsub.prepareReplacement = function(replacement) {
  if (typeof replacement == 'function') return replacement;
  var template = new Template(replacement);
  return function(match) { return template.evaluate(match) };
}

String.prototype.parseQuery = String.prototype.toQueryParams;

var Template = Class.create();
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
Template.prototype = {
  initialize: function(template, pattern) {
    this.template = template.toString();
    this.pattern  = pattern || Template.Pattern;
  },

  evaluate: function(object) {
    return this.template.gsub(this.pattern, function(match) {
      var before = match[1];
      if (before == '\\') return match[2];
      return before + (object[match[3]] || '').toString();
    });
  }
}

var $break    = new Object();
var $continue = new Object();

var Enumerable = {
  each: function(iterator) {
    var index = 0;
    try {
      this._each(function(value) {
        try {
          iterator(value, index++);
        } catch (e) {
          if (e != $continue) throw e;
        }
      });
    } catch (e) {
      if (e != $break) throw e;
    }
  },

  all: function(iterator) {
    var result = true;
    this.each(function(value, index) {
      result = result && !!(iterator || Prototype.K)(value, index);
      if (!result) throw $break;
    });
    return result;
  },

  any: function(iterator) {
    var result = false;
    this.each(function(value, index) {
      if (result = !!(iterator || Prototype.K)(value, index))
        throw $break;
    });
    return result;
  },

  collect: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      results.push(iterator(value, index));
    });
    return results;
  },

  detect: function (iterator) {
    var result;
    this.each(function(value, index) {
      if (iterator(value, index)) {
        result = value;
        throw $break;
      }
    });
    return result;
  },

  findAll: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (iterator(value, index))
        results.push(value);
    });
    return results;
  },

  grep: function(pattern, iterator) {
    var results = [];
    this.each(function(value, index) {
      var stringValue = value.toString();
      if (stringValue.match(pattern))
        results.push((iterator || Prototype.K)(value, index));
    })
    return results;
  },

  include: function(object) {
    var found = false;
    this.each(function(value) {
      if (value == object) {
        found = true;
        throw $break;
      }
    });
    return found;
  },

  inject: function(memo, iterator) {
    this.each(function(value, index) {
      memo = iterator(memo, value, index);
    });
    return memo;
  },

  invoke: function(method) {
    var args = $A(arguments).slice(1);
    return this.collect(function(value) {
      return value[method].apply(value, args);
    });
  },

  max: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (result == undefined || value >= result)
        result = value;
    });
    return result;
  },

  min: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (result == undefined || value < result)
        result = value;
    });
    return result;
  },

  partition: function(iterator) {
    var trues = [], falses = [];
    this.each(function(value, index) {
      ((iterator || Prototype.K)(value, index) ?
        trues : falses).push(value);
    });
    return [trues, falses];
  },

  pluck: function(property) {
    var results = [];
    this.each(function(value, index) {
      results.push(value[property]);
    });
    return results;
  },

  reject: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (!iterator(value, index))
        results.push(value);
    });
    return results;
  },

  sortBy: function(iterator) {
    return this.collect(function(value, index) {
      return {value: value, criteria: iterator(value, index)};
    }).sort(function(left, right) {
      var a = left.criteria, b = right.criteria;
      return a < b ? -1 : a > b ? 1 : 0;
    }).pluck('value');
  },

  toArray: function() {
    return this.collect(Prototype.K);
  },

  zip: function() {
    var iterator = Prototype.K, args = $A(arguments);
    if (typeof args.last() == 'function')
      iterator = args.pop();

    var collections = [this].concat(args).map($A);
    return this.map(function(value, index) {
      return iterator(collections.pluck(index));
    });
  },

  inspect: function() {
    return '#<Enumerable:' + this.toArray().inspect() + '>';
  }
}

Object.extend(Enumerable, {
  map:     Enumerable.collect,
  find:    Enumerable.detect,
  select:  Enumerable.findAll,
  member:  Enumerable.include,
  entries: Enumerable.toArray
});
var $A = Array.from = function(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) {
    return iterable.toArray();
  } else {
    var results = [];
    for (var i = 0; i < iterable.length; i++)
      results.push(iterable[i]);
    return results;
  }
}

Object.extend(Array.prototype, Enumerable);

if (!Array.prototype._reverse)
  Array.prototype._reverse = Array.prototype.reverse;

Object.extend(Array.prototype, {
  _each: function(iterator) {
    for (var i = 0; i < this.length; i++)
      iterator(this[i]);
  },

  clear: function() {
    this.length = 0;
    return this;
  },

  first: function() {
    return this[0];
  },

  last: function() {
    return this[this.length - 1];
  },

  compact: function() {
    return this.select(function(value) {
      return value != undefined || value != null;
    });
  },

  flatten: function() {
    return this.inject([], function(array, value) {
      return array.concat(value && value.constructor == Array ?
        value.flatten() : [value]);
    });
  },

  without: function() {
    var values = $A(arguments);
    return this.select(function(value) {
      return !values.include(value);
    });
  },

  indexOf: function(object) {
    for (var i = 0; i < this.length; i++)
      if (this[i] == object) return i;
    return -1;
  },

  reverse: function(inline) {
    return (inline !== false ? this : this.toArray())._reverse();
  },

  reduce: function() {
    return this.length > 1 ? this : this[0];
  },

  uniq: function() {
    return this.inject([], function(array, value) {
      return array.include(value) ? array : array.concat([value]);
    });
  },

  inspect: function() {
    return '[' + this.map(Object.inspect).join(', ') + ']';
  }
});
var Hash = {
  _each: function(iterator) {
    for (var key in this) {
      var value = this[key];
      if (typeof value == 'function') continue;

      var pair = [key, value];
      pair.key = key;
      pair.value = value;
      iterator(pair);
    }
  },

  keys: function() {
    return this.pluck('key');
  },

  values: function() {
    return this.pluck('value');
  },

  merge: function(hash) {
    return $H(hash).inject($H(this), function(mergedHash, pair) {
      mergedHash[pair.key] = pair.value;
      return mergedHash;
    });
  },

  toQueryString: function() {
    return this.map(function(pair) {
      return pair.map(encodeURIComponent).join('=');
    }).join('&');
  },

  inspect: function() {
    return '#<Hash:{' + this.map(function(pair) {
      return pair.map(Object.inspect).join(': ');
    }).join(', ') + '}>';
  }
}

function $H(object) {
  var hash = Object.extend({}, object || {});
  Object.extend(hash, Enumerable);
  Object.extend(hash, Hash);
  return hash;
}
ObjectRange = Class.create();
Object.extend(ObjectRange.prototype, Enumerable);
Object.extend(ObjectRange.prototype, {
  initialize: function(start, end, exclusive) {
    this.start = start;
    this.end = end;
    this.exclusive = exclusive;
  },

  _each: function(iterator) {
    var value = this.start;
    while (this.include(value)) {
      iterator(value);
      value = value.succ();
    }
  },

  include: function(value) {
    if (value < this.start)
      return false;
    if (this.exclusive)
      return value < this.end;
    return value <= this.end;
  }
});

var $R = function(start, end, exclusive) {
  return new ObjectRange(start, end, exclusive);
}

var Ajax = {
  getTransport: function() {
    return Try.these(
      function() {return new XMLHttpRequest()},
      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')}
    ) || false;
  },

  activeRequestCount: 0
}

Ajax.Responders = {
  responders: [],

  _each: function(iterator) {
    this.responders._each(iterator);
  },

  register: function(responderToAdd) {
    if (!this.include(responderToAdd))
      this.responders.push(responderToAdd);
  },

  unregister: function(responderToRemove) {
    this.responders = this.responders.without(responderToRemove);
  },

  dispatch: function(callback, request, transport, json) {
    this.each(function(responder) {
      if (responder[callback] && typeof responder[callback] == 'function') {
        try {
          responder[callback].apply(responder, [request, transport, json]);
        } catch (e) {}
      }
    });
  }
};

Object.extend(Ajax.Responders, Enumerable);

Ajax.Responders.register({
  onCreate: function() {
    Ajax.activeRequestCount++;
  },

  onComplete: function() {
    Ajax.activeRequestCount--;
  }
});

Ajax.Base = function() {};
Ajax.Base.prototype = {
  setOptions: function(options) {
    this.options = {
      method:       'post',
      asynchronous: true,
      contentType:  'application/x-www-form-urlencoded',
      parameters:   ''
    }
    Object.extend(this.options, options || {});
  },

  responseIsSuccess: function() {
    return this.transport.status == undefined
        || this.transport.status == 0
        || (this.transport.status >= 200 && this.transport.status < 300);
  },

  responseIsFailure: function() {
    return !this.responseIsSuccess();
  }
}

Ajax.Request = Class.create();
Ajax.Request.Events =
  ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];

Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
  initialize: function(url, options) {
    this.transport = Ajax.getTransport();
    this.setOptions(options);
    this.request(url);
  },

  request: function(url) {
    var parameters = this.options.parameters || '';
    if (parameters.length > 0) parameters += '&_=';

    /* Simulate other verbs over post */
    if (this.options.method != 'get' && this.options.method != 'post') {
      parameters += (parameters.length > 0 ? '&' : '') + '_method=' + this.options.method;
      this.options.method = 'post';
    }

    try {
      this.url = url;
      if (this.options.method == 'get' && parameters.length > 0)
        this.url += (this.url.match(/\?/) ? '&' : '?') + parameters;

      Ajax.Responders.dispatch('onCreate', this, this.transport);

      this.transport.open(this.options.method, this.url,
        this.options.asynchronous);

      if (this.options.asynchronous)
        setTimeout(function() { this.respondToReadyState(1) }.bind(this), 10);

      this.transport.onreadystatechange = this.onStateChange.bind(this);
      this.setRequestHeaders();

      var body = this.options.postBody ? this.options.postBody : parameters;
      this.transport.send(this.options.method == 'post' ? body : null);

      /* Force Firefox to handle ready state 4 for synchronous requests */
      if (!this.options.asynchronous && this.transport.overrideMimeType)
        this.onStateChange();

    } catch (e) {
      this.dispatchException(e);
    }
  },

  setRequestHeaders: function() {
    var requestHeaders =
      ['X-Requested-With', 'XMLHttpRequest',
       'X-Prototype-Version', Prototype.Version,
       'Accept', 'text/javascript, text/html, application/xml, text/xml, */*'];

    if (this.options.method == 'post') {
      requestHeaders.push('Content-type', this.options.contentType);

      /* Force "Connection: close" for Mozilla browsers to work around
       * a bug where XMLHttpReqeuest sends an incorrect Content-length
       * header. See Mozilla Bugzilla #246651.
       */
      if (this.transport.overrideMimeType)
        requestHeaders.push('Connection', 'close');
    }

    if (this.options.requestHeaders)
      requestHeaders.push.apply(requestHeaders, this.options.requestHeaders);

    for (var i = 0; i < requestHeaders.length; i += 2)
      this.transport.setRequestHeader(requestHeaders[i], requestHeaders[i+1]);
  },

  onStateChange: function() {
    var readyState = this.transport.readyState;
    if (readyState != 1)
      this.respondToReadyState(this.transport.readyState);
  },

  header: function(name) {
    try {
      return this.transport.getResponseHeader(name);
    } catch (e) {}
  },

  evalJSON: function() {
    try {
      return eval('(' + this.header('X-JSON') + ')');
    } catch (e) {}
  },

  evalResponse: function() {
    try {
      return eval(this.transport.responseText);
    } catch (e) {
      this.dispatchException(e);
    }
  },

  respondToReadyState: function(readyState) {
    var event = Ajax.Request.Events[readyState];
    var transport = this.transport, json = this.evalJSON();

    if (event == 'Complete') {
      try {
        (this.options['on' + this.transport.status]
         || this.options['on' + (this.responseIsSuccess() ? 'Success' : 'Failure')]
         || Prototype.emptyFunction)(transport, json);
      } catch (e) {
        this.dispatchException(e);
      }

      if ((this.header('Content-type') || '').match(/^text\/javascript/i))
        this.evalResponse();
    }

    try {
      (this.options['on' + event] || Prototype.emptyFunction)(transport, json);
      Ajax.Responders.dispatch('on' + event, this, transport, json);
    } catch (e) {
      this.dispatchException(e);
    }

    /* Avoid memory leak in MSIE: clean up the oncomplete event handler */
    if (event == 'Complete')
      this.transport.onreadystatechange = Prototype.emptyFunction;
  },

  dispatchException: function(exception) {
    (this.options.onException || Prototype.emptyFunction)(this, exception);
    Ajax.Responders.dispatch('onException', this, exception);
  }
});

Ajax.Updater = Class.create();

Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
  initialize: function(container, url, options) {
    this.containers = {
      success: container.success ? $(container.success) : $(container),
      failure: container.failure ? $(container.failure) :
        (container.success ? null : $(container))
    }

    this.transport = Ajax.getTransport();
    this.setOptions(options);

    var onComplete = this.options.onComplete || Prototype.emptyFunction;
    this.options.onComplete = (function(transport, object) {
      this.updateContent();
      onComplete(transport, object);
    }).bind(this);

    this.request(url);
  },

  updateContent: function() {
    var receiver = this.responseIsSuccess() ?
      this.containers.success : this.containers.failure;
    var response = this.transport.responseText;

    if (!this.options.evalScripts)
      response = response.stripScripts();

    if (receiver) {
      if (this.options.insertion) {
        new this.options.insertion(receiver, response);
      } else {
        Element.update(receiver, response);
      }
    }

    if (this.responseIsSuccess()) {
      if (this.onComplete)
        setTimeout(this.onComplete.bind(this), 10);
    }
  }
});

Ajax.PeriodicalUpdater = Class.create();
Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), {
  initialize: function(container, url, options) {
    this.setOptions(options);
    this.onComplete = this.options.onComplete;

    this.frequency = (this.options.frequency || 2);
    this.decay = (this.options.decay || 1);

    this.updater = {};
    this.container = container;
    this.url = url;

    this.start();
  },

  start: function() {
    this.options.onComplete = this.updateComplete.bind(this);
    this.onTimerEvent();
  },

  stop: function() {
    this.updater.options.onComplete = undefined;
    clearTimeout(this.timer);
    (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
  },

  updateComplete: function(request) {
    if (this.options.decay) {
      this.decay = (request.responseText == this.lastText ?
        this.decay * this.options.decay : 1);

      this.lastText = request.responseText;
    }
    this.timer = setTimeout(this.onTimerEvent.bind(this),
      this.decay * this.frequency * 1000);
  },

  onTimerEvent: function() {
    this.updater = new Ajax.Updater(this.container, this.url, this.options);
  }
});
function $() {
  var results = [], element;
  for (var i = 0; i < arguments.length; i++) {
    element = arguments[i];
    if (typeof element == 'string')
      element = document.getElementById(element);
    results.push(Element.extend(element));
  }
  return results.reduce();
}

document.getElementsByClassName = function(className, parentElement) {
  var children = ($(parentElement) || document.body).getElementsByTagName('*');
  return $A(children).inject([], function(elements, child) {
    if (child.className.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
      elements.push(Element.extend(child));
    return elements;
  });
}

/*--------------------------------------------------------------------------*/

if (!window.Element)
  var Element = new Object();

Element.extend = function(element) {
  if (!element) return;
  if (_nativeExtensions || element.nodeType == 3) return element;

  if (!element._extended && element.tagName && element != window) {
    var methods = Object.clone(Element.Methods), cache = Element.extend.cache;

    if (element.tagName == 'FORM')
      Object.extend(methods, Form.Methods);
    if (['INPUT', 'TEXTAREA', 'SELECT'].include(element.tagName))
      Object.extend(methods, Form.Element.Methods);

    for (var property in methods) {
      var value = methods[property];
      if (typeof value == 'function')
        element[property] = cache.findOrStore(value);
    }
  }

  element._extended = true;
  return element;
}

Element.extend.cache = {
  findOrStore: function(value) {
    return this[value] = this[value] || function() {
      return value.apply(null, [this].concat($A(arguments)));
    }
  }
}

Element.Methods = {
  visible: function(element) {
    return $(element).style.display != 'none';
  },

  toggle: function(element) {
    element = $(element);
    Element[Element.visible(element) ? 'hide' : 'show'](element);
    return element;
  },

  hide: function(element) {
    $(element).style.display = 'none';
    return element;
  },

  show: function(element) {
    $(element).style.display = '';
    return element;
  },

  remove: function(element) {
    element = $(element);
    element.parentNode.removeChild(element);
    return element;
  },

  update: function(element, html) {
    $(element).innerHTML = html.stripScripts();
    setTimeout(function() {html.evalScripts()}, 10);
    return element;
  },

  replace: function(element, html) {
    element = $(element);
    if (element.outerHTML) {
      element.outerHTML = html.stripScripts();
    } else {
      var range = element.ownerDocument.createRange();
      range.selectNodeContents(element);
      element.parentNode.replaceChild(
        range.createContextualFragment(html.stripScripts()), element);
    }
    setTimeout(function() {html.evalScripts()}, 10);
    return element;
  },

  inspect: function(element) {
    element = $(element);
    var result = '<' + element.tagName.toLowerCase();
    $H({'id': 'id', 'className': 'class'}).each(function(pair) {
      var property = pair.first(), attribute = pair.last();
      var value = (element[property] || '').toString();
      if (value) result += ' ' + attribute + '=' + value.inspect(true);
    });
    return result + '>';
  },

  recursivelyCollect: function(element, property) {
    element = $(element);
    var elements = [];
    while (element = element[property])
      if (element.nodeType == 1)
        elements.push(Element.extend(element));
    return elements;
  },

  ancestors: function(element) {
    return $(element).recursivelyCollect('parentNode');
  },

  descendants: function(element) {
    element = $(element);
    return $A(element.getElementsByTagName('*'));
  },

  previousSiblings: function(element) {
    return $(element).recursivelyCollect('previousSibling');
  },

  nextSiblings: function(element) {
    return $(element).recursivelyCollect('nextSibling');
  },

  siblings: function(element) {
    element = $(element);
    return element.previousSiblings().reverse().concat(element.nextSiblings());
  },

  match: function(element, selector) {
    element = $(element);
    if (typeof selector == 'string')
      selector = new Selector(selector);
    return selector.match(element);
  },

  up: function(element, expression, index) {
    return Selector.findElement($(element).ancestors(), expression, index);
  },

  down: function(element, expression, index) {
    return Selector.findElement($(element).descendants(), expression, index);
  },

  previous: function(element, expression, index) {
    return Selector.findElement($(element).previousSiblings(), expression, index);
  },

  next: function(element, expression, index) {
    return Selector.findElement($(element).nextSiblings(), expression, index);
  },

  getElementsBySelector: function() {
    var args = $A(arguments), element = $(args.shift());
    return Selector.findChildElements(element, args);
  },

  getElementsByClassName: function(element, className) {
    element = $(element);
    return document.getElementsByClassName(className, element);
  },

  getHeight: function(element) {
    element = $(element);
    return element.offsetHeight;
  },

  classNames: function(element) {
    return new Element.ClassNames(element);
  },

  hasClassName: function(element, className) {
    if (!(element = $(element))) return;
    return Element.classNames(element).include(className);
  },

  addClassName: function(element, className) {
    if (!(element = $(element))) return;
    Element.classNames(element).add(className);
    return element;
  },

  removeClassName: function(element, className) {
    if (!(element = $(element))) return;
    Element.classNames(element).remove(className);
    return element;
  },

  observe: function() {
    Event.observe.apply(Event, arguments);
    return $A(arguments).first();
  },

  stopObserving: function() {
    Event.stopObserving.apply(Event, arguments);
    return $A(arguments).first();
  },

  // removes whitespace-only text node children
  cleanWhitespace: function(element) {
    element = $(element);
    var node = element.firstChild;
    while (node) {
      var nextNode = node.nextSibling;
      if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
        element.removeChild(node);
      node = nextNode;
    }
    return element;
  },

  empty: function(element) {
    return $(element).innerHTML.match(/^\s*$/);
  },

  childOf: function(element, ancestor) {
    element = $(element), ancestor = $(ancestor);
    while (element = element.parentNode)
      if (element == ancestor) return true;
    return false;
  },

  scrollTo: function(element) {
    element = $(element);
    var x = element.x ? element.x : element.offsetLeft,
        y = element.y ? element.y : element.offsetTop;
    window.scrollTo(x, y);
    return element;
  },

  getStyle: function(element, style) {
    element = $(element);
    var value = element.style[style.camelize()];
    if (!value) {
      if (document.defaultView && document.defaultView.getComputedStyle) {
        var css = document.defaultView.getComputedStyle(element, null);
        value = css ? css.getPropertyValue(style) : null;
      } else if (element.currentStyle) {
        value = element.currentStyle[style.camelize()];
      }
    }

    if (window.opera && ['left', 'top', 'right', 'bottom'].include(style))
      if (Element.getStyle(element, 'position') == 'static') value = 'auto';

    return value == 'auto' ? null : value;
  },

  setStyle: function(element, style) {
    element = $(element);
    for (var name in style)
      element.style[name.camelize()] = style[name];
    return element;
  },

  getDimensions: function(element) {
    element = $(element);
    if (Element.getStyle(element, 'display') != 'none')
      return {width: element.offsetWidth, height: element.offsetHeight};

    // All *Width and *Height properties give 0 on elements with display none,
    // so enable the element temporarily
    var els = element.style;
    var originalVisibility = els.visibility;
    var originalPosition = els.position;
    els.visibility = 'hidden';
    els.position = 'absolute';
    els.display = '';
    var originalWidth = element.clientWidth;
    var originalHeight = element.clientHeight;
    els.display = 'none';
    els.position = originalPosition;
    els.visibility = originalVisibility;
    return {width: originalWidth, height: originalHeight};
  },

  makePositioned: function(element) {
    element = $(element);
    var pos = Element.getStyle(element, 'position');
    if (pos == 'static' || !pos) {
      element._madePositioned = true;
      element.style.position = 'relative';
      // Opera returns the offset relative to the positioning context, when an
      // element is position relative but top and left have not been defined
      if (window.opera) {
        element.style.top = 0;
        element.style.left = 0;
      }
    }
    return element;
  },

  undoPositioned: function(element) {
    element = $(element);
    if (element._madePositioned) {
      element._madePositioned = undefined;
      element.style.position =
        element.style.top =
        element.style.left =
        element.style.bottom =
        element.style.right = '';
    }
    return element;
  },

  makeClipping: function(element) {
    element = $(element);
    if (element._overflow) return;
    element._overflow = element.style.overflow || 'auto';
    if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden')
      element.style.overflow = 'hidden';
    return element;
  },

  undoClipping: function(element) {
    element = $(element);
    if (!element._overflow) return;
    element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
    element._overflow = null;
    return element;
  }
}

// IE is missing .innerHTML support for TABLE-related elements
if(document.all){
  Element.Methods.update = function(element, html) {
    element = $(element);
    var tagName = element.tagName.toUpperCase();
    if (['THEAD','TBODY','TR','TD'].indexOf(tagName) > -1) {
      var div = document.createElement('div');
      switch (tagName) {
        case 'THEAD':
        case 'TBODY':
          div.innerHTML = '<table><tbody>' +  html.stripScripts() + '</tbody></table>';
          depth = 2;
          break;
        case 'TR':
          div.innerHTML = '<table><tbody><tr>' +  html.stripScripts() + '</tr></tbody></table>';
          depth = 3;
          break;
        case 'TD':
          div.innerHTML = '<table><tbody><tr><td>' +  html.stripScripts() + '</td></tr></tbody></table>';
          depth = 4;
      }
      $A(element.childNodes).each(function(node){
        element.removeChild(node)
      });
      depth.times(function(){ div = div.firstChild });

      $A(div.childNodes).each(
        function(node){ element.appendChild(node) });
    } else {
      element.innerHTML = html.stripScripts();
    }
    setTimeout(function() {html.evalScripts()}, 10);
    return element;
  }
}

Object.extend(Element, Element.Methods);

var _nativeExtensions = false;

if (!window.HTMLElement && /Konqueror|Safari|KHTML/.test(navigator.userAgent)) {
  /* Emulate HTMLElement, HTMLFormElement, HTMLInputElement, HTMLTextAreaElement,
     and HTMLSelectElement in Safari */
  ['', 'Form', 'Input', 'TextArea', 'Select'].each(function(tag) {
    var klass = window['HTML' + tag + 'Element'] = {};
    klass.prototype = document.createElement(tag ? tag.toLowerCase() : 'div').__proto__;
  });
}

Element.addMethods = function(methods) {
  Object.extend(Element.Methods, methods || {});

  function copy(methods, destination) {
    var cache = Element.extend.cache;
    for (var property in methods) {
      var value = methods[property];
      destination[property] = cache.findOrStore(value);
    }
  }

  if (typeof HTMLElement != 'undefined') {
    copy(Element.Methods, HTMLElement.prototype);
    copy(Form.Methods, HTMLFormElement.prototype);
    [HTMLInputElement, HTMLTextAreaElement, HTMLSelectElement].each(function(klass) {
      copy(Form.Element.Methods, klass.prototype);
    });
    _nativeExtensions = true;
  }
}

var Toggle = new Object();
Toggle.display = Element.toggle;

/*--------------------------------------------------------------------------*/

Abstract.Insertion = function(adjacency) {
  this.adjacency = adjacency;
}

Abstract.Insertion.prototype = {
  initialize: function(element, content) {
    this.element = $(element);
    this.content = content.stripScripts();

    if (this.adjacency && this.element.insertAdjacentHTML) {
      try {
        this.element.insertAdjacentHTML(this.adjacency, this.content);
      } catch (e) {
        var tagName = this.element.tagName.toLowerCase();
        if (tagName == 'tbody' || tagName == 'tr') {
          this.insertContent(this.contentFromAnonymousTable());
        } else {
          throw e;
        }
      }
    } else {
      this.range = this.element.ownerDocument.createRange();
      if (this.initializeRange) this.initializeRange();
      this.insertContent([this.range.createContextualFragment(this.content)]);
    }

    setTimeout(function() {content.evalScripts()}, 10);
  },

  contentFromAnonymousTable: function() {
    var div = document.createElement('div');
    div.innerHTML = '<table><tbody>' + this.content + '</tbody></table>';
    return $A(div.childNodes[0].childNodes[0].childNodes);
  }
}

var Insertion = new Object();

Insertion.Before = Class.create();
Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), {
  initializeRange: function() {
    this.range.setStartBefore(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.parentNode.insertBefore(fragment, this.element);
    }).bind(this));
  }
});

Insertion.Top = Class.create();
Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), {
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(true);
  },

  insertContent: function(fragments) {
    fragments.reverse(false).each((function(fragment) {
      this.element.insertBefore(fragment, this.element.firstChild);
    }).bind(this));
  }
});

Insertion.Bottom = Class.create();
Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), {
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.appendChild(fragment);
    }).bind(this));
  }
});

Insertion.After = Class.create();
Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), {
  initializeRange: function() {
    this.range.setStartAfter(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.parentNode.insertBefore(fragment,
        this.element.nextSibling);
    }).bind(this));
  }
});

/*--------------------------------------------------------------------------*/

Element.ClassNames = Class.create();
Element.ClassNames.prototype = {
  initialize: function(element) {
    this.element = $(element);
  },

  _each: function(iterator) {
    this.element.className.split(/\s+/).select(function(name) {
      return name.length > 0;
    })._each(iterator);
  },

  set: function(className) {
    this.element.className = className;
  },

  add: function(classNameToAdd) {
    if (this.include(classNameToAdd)) return;
    this.set(this.toArray().concat(classNameToAdd).join(' '));
  },

  remove: function(classNameToRemove) {
    if (!this.include(classNameToRemove)) return;
    this.set(this.select(function(className) {
      return className != classNameToRemove;
    }).join(' '));
  },

  toString: function() {
    return this.toArray().join(' ');
  }
}

Object.extend(Element.ClassNames.prototype, Enumerable);
var Selector = Class.create();
Selector.prototype = {
  initialize: function(expression) {
    this.params = {classNames: []};
    this.expression = expression.toString().strip();
    this.parseExpression();
    this.compileMatcher();
  },

  parseExpression: function() {
    function abort(message) { throw 'Parse error in selector: ' + message; }

    if (this.expression == '')  abort('empty expression');

    var params = this.params, expr = this.expression, match, modifier, clause, rest;
    while (match = expr.match(/^(.*)\[([a-z0-9_:-]+?)(?:([~\|!]?=)(?:"([^"]*)"|([^\]\s]*)))?\]$/i)) {
      params.attributes = params.attributes || [];
      params.attributes.push({name: match[2], operator: match[3], value: match[4] || match[5] || ''});
      expr = match[1];
    }

    if (expr == '*') return this.params.wildcard = true;

    while (match = expr.match(/^([^a-z0-9_-])?([a-z0-9_-]+)(.*)/i)) {
      modifier = match[1], clause = match[2], rest = match[3];
      switch (modifier) {
        case '#':       params.id = clause; break;
        case '.':       params.classNames.push(clause); break;
        case '':
        case undefined: params.tagName = clause.toUpperCase(); break;
        default:        abort(expr.inspect());
      }
      expr = rest;
    }

    if (expr.length > 0) abort(expr.inspect());
  },

  buildMatchExpression: function() {
    var params = this.params, conditions = [], clause;

    if (params.wildcard)
      conditions.push('true');
    if (clause = params.id)
      conditions.push('element.id == ' + clause.inspect());
    if (clause = params.tagName)
      conditions.push('element.tagName.toUpperCase() == ' + clause.inspect());
    if ((clause = params.classNames).length > 0)
      for (var i = 0; i < clause.length; i++)
        conditions.push('Element.hasClassName(element, ' + clause[i].inspect() + ')');
    if (clause = params.attributes) {
      clause.each(function(attribute) {
        var value = 'element.getAttribute(' + attribute.name.inspect() + ')';
        var splitValueBy = function(delimiter) {
          return value + ' && ' + value + '.split(' + delimiter.inspect() + ')';
        }

        switch (attribute.operator) {
          case '=':       conditions.push(value + ' == ' + attribute.value.inspect()); break;
          case '~=':      conditions.push(splitValueBy(' ') + '.include(' + attribute.value.inspect() + ')'); break;
          case '|=':      conditions.push(
                            splitValueBy('-') + '.first().toUpperCase() == ' + attribute.value.toUpperCase().inspect()
                          ); break;
          case '!=':      conditions.push(value + ' != ' + attribute.value.inspect()); break;
          case '':
          case undefined: conditions.push(value + ' != null'); break;
          default:        throw 'Unknown operator ' + attribute.operator + ' in selector';
        }
      });
    }

    return conditions.join(' && ');
  },

  compileMatcher: function() {
    this.match = new Function('element', 'if (!element.tagName) return false; \
      return ' + this.buildMatchExpression());
  },

  findElements: function(scope) {
    var element;

    if (element = $(this.params.id))
      if (this.match(element))
        if (!scope || Element.childOf(element, scope))
          return [element];

    scope = (scope || document).getElementsByTagName(this.params.tagName || '*');

    var results = [];
    for (var i = 0; i < scope.length; i++)
      if (this.match(element = scope[i]))
        results.push(Element.extend(element));

    return results;
  },

  toString: function() {
    return this.expression;
  }
}

Object.extend(Selector, {
  matchElements: function(elements, expression) {
    var selector = new Selector(expression);
    return elements.select(selector.match.bind(selector));
  },

  findElement: function(elements, expression, index) {
    if (typeof expression == 'number') index = expression, expression = false;
    return Selector.matchElements(elements, expression || '*')[index || 0];
  },

  findChildElements: function(element, expressions) {
    return expressions.map(function(expression) {
      return expression.strip().split(/\s+/).inject([null], function(results, expr) {
        var selector = new Selector(expr);
        return results.inject([], function(elements, result) {
          return elements.concat(selector.findElements(result || element));
        });
      });
    }).flatten();
  }
});

function $$() {
  return Selector.findChildElements(document, $A(arguments));
}
var Form = {
  reset: function(form) {
    $(form).reset();
    return form;
  }
};

Form.Methods = {
  serialize: function(form) {
    var elements = Form.getElements($(form));
    var queryComponents = new Array();

    for (var i = 0; i < elements.length; i++) {
      var queryComponent = Form.Element.serialize(elements[i]);
      if (queryComponent)
        queryComponents.push(queryComponent);
    }

    return queryComponents.join('&');
  },

  getElements: function(form) {
    form = $(form);
    var elements = new Array();

    for (var tagName in Form.Element.Serializers) {
      var tagElements = form.getElementsByTagName(tagName);
      for (var j = 0; j < tagElements.length; j++)
        elements.push(tagElements[j]);
    }
    return elements;
  },

  getInputs: function(form, typeName, name) {
    form = $(form);
    var inputs = form.getElementsByTagName('input');

    if (!typeName && !name)
      return inputs;

    var matchingInputs = new Array();
    for (var i = 0; i < inputs.length; i++) {
      var input = inputs[i];
      if ((typeName && input.type != typeName) ||
          (name && input.name != name))
        continue;
      matchingInputs.push(input);
    }

    return matchingInputs;
  },

  disable: function(form) {
    form = $(form);
    var elements = Form.getElements(form);
    for (var i = 0; i < elements.length; i++) {
      var element = elements[i];
      element.blur();
      element.disabled = 'true';
    }
    return form;
  },

  enable: function(form) {
    form = $(form);
    var elements = Form.getElements(form);
    for (var i = 0; i < elements.length; i++) {
      var element = elements[i];
      element.disabled = '';
    }
    return form;
  },

  findFirstElement: function(form) {
    return Form.getElements(form).find(function(element) {
      return element.type != 'hidden' && !element.disabled &&
        ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
    });
  },

  focusFirstElement: function(form) {
    form = $(form);
    Field.activate(Form.findFirstElement(form));
    return form;
  }
}

Object.extend(Form, Form.Methods);

/*--------------------------------------------------------------------------*/

Form.Element = {
  focus: function(element) {
    $(element).focus();
    return element;
  },

  select: function(element) {
    $(element).select();
    return element;
  }
}

Form.Element.Methods = {
  serialize: function(element) {
    element = $(element);
    var method = element.tagName.toLowerCase();
    var parameter = Form.Element.Serializers[method](element);

    if (parameter) {
      var key = encodeURIComponent(parameter[0]);
      if (key.length == 0) return;

      if (parameter[1].constructor != Array)
        parameter[1] = [parameter[1]];

      return parameter[1].map(function(value) {
        return key + '=' + encodeURIComponent(value);
      }).join('&');
    }
  },

  getValue: function(element) {
    element = $(element);
    var method = element.tagName.toLowerCase();
    var parameter = Form.Element.Serializers[method](element);

    if (parameter)
      return parameter[1];
  },

  clear: function(element) {
    $(element).value = '';
    return element;
  },

  present: function(element) {
    return $(element).value != '';
  },

  activate: function(element) {
    element = $(element);
    element.focus();
    if (element.select)
      element.select();
    return element;
  },

  disable: function(element) {
    element = $(element);
    element.disabled = '';
    return element;
  },

  enable: function(element) {
    element = $(element);
    element.blur();
    element.disabled = 'true';
    return element;
  }
}

Object.extend(Form.Element, Form.Element.Methods);
var Field = Form.Element;

/*--------------------------------------------------------------------------*/

Form.Element.Serializers = {
  input: function(element) {
    switch (element.type.toLowerCase()) {
      case 'checkbox':
      case 'radio':
        return Form.Element.Serializers.inputSelector(element);
      default:
        return Form.Element.Serializers.textarea(element);
    }
    return false;
  },

  inputSelector: function(element) {
    if (element.checked)
      return [element.name, element.value];
  },

  textarea: function(element) {
    return [element.name, element.value];
  },

  select: function(element) {
    return Form.Element.Serializers[element.type == 'select-one' ?
      'selectOne' : 'selectMany'](element);
  },

  selectOne: function(element) {
    var value = '', opt, index = element.selectedIndex;
    if (index >= 0) {
      opt = element.options[index];
      value = opt.value || opt.text;
    }
    return [element.name, value];
  },

  selectMany: function(element) {
    var value = [];
    for (var i = 0; i < element.length; i++) {
      var opt = element.options[i];
      if (opt.selected)
        value.push(opt.value || opt.text);
    }
    return [element.name, value];
  }
}

/*--------------------------------------------------------------------------*/

var $F = Form.Element.getValue;

/*--------------------------------------------------------------------------*/

Abstract.TimedObserver = function() {}
Abstract.TimedObserver.prototype = {
  initialize: function(element, frequency, callback) {
    this.frequency = frequency;
    this.element   = $(element);
    this.callback  = callback;

    this.lastValue = this.getValue();
    this.registerCallback();
  },

  registerCallback: function() {
    setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  onTimerEvent: function() {
    var value = this.getValue();
    if (this.lastValue != value) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  }
}

Form.Element.Observer = Class.create();
Form.Element.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.Observer = Class.create();
Form.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
  getValue: function() {
    return Form.serialize(this.element);
  }
});

/*--------------------------------------------------------------------------*/

Abstract.EventObserver = function() {}
Abstract.EventObserver.prototype = {
  initialize: function(element, callback) {
    this.element  = $(element);
    this.callback = callback;

    this.lastValue = this.getValue();
    if (this.element.tagName.toLowerCase() == 'form')
      this.registerFormCallbacks();
    else
      this.registerCallback(this.element);
  },

  onElementEvent: function() {
    var value = this.getValue();
    if (this.lastValue != value) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  },

  registerFormCallbacks: function() {
    var elements = Form.getElements(this.element);
    for (var i = 0; i < elements.length; i++)
      this.registerCallback(elements[i]);
  },

  registerCallback: function(element) {
    if (element.type) {
      switch (element.type.toLowerCase()) {
        case 'checkbox':
        case 'radio':
          Event.observe(element, 'click', this.onElementEvent.bind(this));
          break;
        default:
          Event.observe(element, 'change', this.onElementEvent.bind(this));
          break;
      }
    }
  }
}

Form.Element.EventObserver = Class.create();
Form.Element.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.EventObserver = Class.create();
Form.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
  getValue: function() {
    return Form.serialize(this.element);
  }
});
if (!window.Event) {
  var Event = new Object();
}

Object.extend(Event, {
  KEY_BACKSPACE: 8,
  KEY_TAB:       9,
  KEY_RETURN:   13,
  KEY_ESC:      27,
  KEY_LEFT:     37,
  KEY_UP:       38,
  KEY_RIGHT:    39,
  KEY_DOWN:     40,
  KEY_DELETE:   46,
  KEY_HOME:     36,
  KEY_END:      35,
  KEY_PAGEUP:   33,
  KEY_PAGEDOWN: 34,

  element: function(event) {
    return event.target || event.srcElement;
  },

  isLeftClick: function(event) {
    return (((event.which) && (event.which == 1)) ||
            ((event.button) && (event.button == 1)));
  },

  pointerX: function(event) {
    return event.pageX || (event.clientX +
      (document.documentElement.scrollLeft || document.body.scrollLeft));
  },

  pointerY: function(event) {
    return event.pageY || (event.clientY +
      (document.documentElement.scrollTop || document.body.scrollTop));
  },

  stop: function(event) {
    if (event.preventDefault) {
      event.preventDefault();
      event.stopPropagation();
    } else {
      event.returnValue = false;
      event.cancelBubble = true;
    }
  },

  // find the first node with the given tagName, starting from the
  // node the event was triggered on; traverses the DOM upwards
  findElement: function(event, tagName) {
    var element = Event.element(event);
    while (element.parentNode && (!element.tagName ||
        (element.tagName.toUpperCase() != tagName.toUpperCase())))
      element = element.parentNode;
    return element;
  },

  observers: false,

  _observeAndCache: function(element, name, observer, useCapture) {
    if (!this.observers) this.observers = [];
    if (element.addEventListener) {
      this.observers.push([element, name, observer, useCapture]);
      element.addEventListener(name, observer, useCapture);
    } else if (element.attachEvent) {
      this.observers.push([element, name, observer, useCapture]);
      element.attachEvent('on' + name, observer);
    }
  },

  unloadCache: function() {
    if (!Event.observers) return;
    for (var i = 0; i < Event.observers.length; i++) {
      Event.stopObserving.apply(this, Event.observers[i]);
      Event.observers[i][0] = null;
    }
    Event.observers = false;
  },

  observe: function(element, name, observer, useCapture) {
    element = $(element);
    useCapture = useCapture || false;

    if (name == 'keypress' &&
        (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
        || element.attachEvent))
      name = 'keydown';

    Event._observeAndCache(element, name, observer, useCapture);
  },

  stopObserving: function(element, name, observer, useCapture) {
    element = $(element);
    useCapture = useCapture || false;

    if (name == 'keypress' &&
        (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
        || element.detachEvent))
      name = 'keydown';

    if (element.removeEventListener) {
      element.removeEventListener(name, observer, useCapture);
    } else if (element.detachEvent) {
      try {
        element.detachEvent('on' + name, observer);
      } catch (e) {}
    }
  }
});

/* prevent memory leaks in IE */
if (navigator.appVersion.match(/\bMSIE\b/))
  Event.observe(window, 'unload', Event.unloadCache, false);
var Position = {
  // set to true if needed, warning: firefox performance problems
  // NOT neeeded for page scrolling, only if draggable contained in
  // scrollable elements
  includeScrollOffsets: false,

  // must be called before calling withinIncludingScrolloffset, every time the
  // page is scrolled
  prepare: function() {
    this.deltaX =  window.pageXOffset
                || document.documentElement.scrollLeft
                || document.body.scrollLeft
                || 0;
    this.deltaY =  window.pageYOffset
                || document.documentElement.scrollTop
                || document.body.scrollTop
                || 0;
  },

  realOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.scrollTop  || 0;
      valueL += element.scrollLeft || 0;
      element = element.parentNode;
    } while (element);
    return [valueL, valueT];
  },

  cumulativeOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
    } while (element);
    return [valueL, valueT];
  },

  positionedOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
      if (element) {
        p = Element.getStyle(element, 'position');
        if (p == 'relative' || p == 'absolute') break;
      }
    } while (element);
    return [valueL, valueT];
  },

  offsetParent: function(element) {
    if (element.offsetParent) return element.offsetParent;
    if (element == document.body) return element;

    while ((element = element.parentNode) && element != document.body)
      if (Element.getStyle(element, 'position') != 'static')
        return element;

    return document.body;
  },

  // caches x/y coordinate pair to use with overlap
  within: function(element, x, y) {
    if (this.includeScrollOffsets)
      return this.withinIncludingScrolloffsets(element, x, y);
    this.xcomp = x;
    this.ycomp = y;
    this.offset = this.cumulativeOffset(element);

    return (y >= this.offset[1] &&
            y <  this.offset[1] + element.offsetHeight &&
            x >= this.offset[0] &&
            x <  this.offset[0] + element.offsetWidth);
  },

  withinIncludingScrolloffsets: function(element, x, y) {
    var offsetcache = this.realOffset(element);

    this.xcomp = x + offsetcache[0] - this.deltaX;
    this.ycomp = y + offsetcache[1] - this.deltaY;
    this.offset = this.cumulativeOffset(element);

    return (this.ycomp >= this.offset[1] &&
            this.ycomp <  this.offset[1] + element.offsetHeight &&
            this.xcomp >= this.offset[0] &&
            this.xcomp <  this.offset[0] + element.offsetWidth);
  },

  // within must be called directly before
  overlap: function(mode, element) {
    if (!mode) return 0;
    if (mode == 'vertical')
      return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
        element.offsetHeight;
    if (mode == 'horizontal')
      return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
        element.offsetWidth;
  },

  page: function(forElement) {
    var valueT = 0, valueL = 0;

    var element = forElement;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;

      // Safari fix
      if (element.offsetParent==document.body)
        if (Element.getStyle(element,'position')=='absolute') break;

    } while (element = element.offsetParent);

    element = forElement;
    do {
      if (!window.opera || element.tagName=='BODY') {
        valueT -= element.scrollTop  || 0;
        valueL -= element.scrollLeft || 0;
      }
    } while (element = element.parentNode);

    return [valueL, valueT];
  },

  clone: function(source, target) {
    var options = Object.extend({
      setLeft:    true,
      setTop:     true,
      setWidth:   true,
      setHeight:  true,
      offsetTop:  0,
      offsetLeft: 0
    }, arguments[2] || {})

    // find page position of source
    source = $(source);
    var p = Position.page(source);

    // find coordinate system to use
    target = $(target);
    var delta = [0, 0];
    var parent = null;
    // delta [0,0] will do fine with position: fixed elements,
    // position:absolute needs offsetParent deltas
    if (Element.getStyle(target,'position') == 'absolute') {
      parent = Position.offsetParent(target);
      delta = Position.page(parent);
    }

    // correct by body offsets (fixes Safari)
    if (parent == document.body) {
      delta[0] -= document.body.offsetLeft;
      delta[1] -= document.body.offsetTop;
    }

    // set position
    if(options.setLeft)   target.style.left  = (p[0] - delta[0] + options.offsetLeft) + 'px';
    if(options.setTop)    target.style.top   = (p[1] - delta[1] + options.offsetTop) + 'px';
    if(options.setWidth)  target.style.width = source.offsetWidth + 'px';
    if(options.setHeight) target.style.height = source.offsetHeight + 'px';
  },

  absolutize: function(element) {
    element = $(element);
    if (element.style.position == 'absolute') return;
    Position.prepare();

    var offsets = Position.positionedOffset(element);
    var top     = offsets[1];
    var left    = offsets[0];
    var width   = element.clientWidth;
    var height  = element.clientHeight;

    element._originalLeft   = left - parseFloat(element.style.left  || 0);
    element._originalTop    = top  - parseFloat(element.style.top || 0);
    element._originalWidth  = element.style.width;
    element._originalHeight = element.style.height;

    element.style.position = 'absolute';
    element.style.top    = top + 'px';;
    element.style.left   = left + 'px';;
    element.style.width  = width + 'px';;
    element.style.height = height + 'px';;
  },

  relativize: function(element) {
    element = $(element);
    if (element.style.position == 'relative') return;
    Position.prepare();

    element.style.position = 'relative';
    var top  = parseFloat(element.style.top  || 0) - (element._originalTop || 0);
    var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);

    element.style.top    = top + 'px';
    element.style.left   = left + 'px';
    element.style.height = element._originalHeight;
    element.style.width  = element._originalWidth;
  }
}

// Safari returns margins on body which is incorrect if the child is absolutely
// positioned.  For performance reasons, redefine Position.cumulativeOffset for
// KHTML/WebKit only.
if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) {
  Position.cumulativeOffset = function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      if (element.offsetParent == document.body)
        if (Element.getStyle(element, 'position') == 'absolute') break;

      element = element.offsetParent;
    } while (element);

    return [valueL, valueT];
  }
}

Element.addMethods();
/***********************************************
* Dynamic Ajax Content- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
// depends on the prototype lib!!!
var bustcachevar = 0; //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadedobjects = "";
var rootdomain = "http://" + window.location.hostName;
var bustcacheparameter = "";
var isajaxpostback = false;
var ajaxcontent = "";
var ajaxpageaction = "";

function ajaxpage(url, containerid, formmethod, params) {
	var page_request = false;
	if (window.XMLHttpRequest) // if Mozilla, Safari etc
		page_request = new XMLHttpRequest()
	else if (window.ActiveXObject){ // if IE
		try {
			page_request = new ActiveXObject("Msxml2.XMLHTTP")
		} catch (e){
			try{
				page_request = new ActiveXObject("Microsoft.XMLHTTP")
			} catch (e){}
		}
	}
	else
		return false
	page_request.onreadystatechange=function(){
		loadpage(page_request, containerid)
	}
	if (bustcachevar) //if bust caching of external page
		bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
	//page_request.setRequestHeader( label, value );
	page_request.open(formmethod, url+bustcacheparameter, true)
	if (typeof params == "undefined") {
		page_request.send(null)
	} else {
		page_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
		page_request.setRequestHeader("Content-length", params.length)
		page_request.setRequestHeader("Connection", "close")
		page_request.send(params)
	}
	return true
}

function loadpage(page_request, containerid) {
	if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)) {
		ajaxcontent = page_request.responseText;
		document.getElementById(containerid).innerHTML = ajaxcontent;
	}
}

function loadobjs() {
	if (!document.getElementById)
		return
	for (i=0; i<arguments.length; i++) {
		var file=arguments[i]
		var fileref=""
		if (loadedobjects.indexOf(file)==-1) { //Check to see if this object has not already been added to page before proceeding
			if (file.indexOf(".js")!=-1) { //If object is a js file
				fileref=document.createElement('script')
				fileref.setAttribute("type","text/javascript");
				fileref.setAttribute("src", file);
			} else if (file.indexOf(".css")!=-1){ //If object is a css file
				fileref=document.createElement("link")
				fileref.setAttribute("rel", "stylesheet");
				fileref.setAttribute("type", "text/css");
				fileref.setAttribute("href", file);
			}
		}
		if (fileref!=""){
			document.getElementsByTagName("head").item(0).appendChild(fileref)
			loadedobjects+=file+" " //Remember this object as being already added to page
		}
	}
}

function Postback(form, containerid) {
	if (isajaxpostback) {
		var params = Form.serialize(form);	// depends on the prototype lib
		return AjaxPost(containerid, params);
	}	else {
		return true;
	}
}

function PostbackLink(formname, containerid, linkid) {
	var form = document.forms[formname];
	qs = Form.serialize(form);	// depends on the prototype lib
	qs += "&__SNPEPortletSubmitLink=" + formname + "_" + linkid; // SNPE hacking!
	if (isajaxpostback)
		AjaxPost(containerid, qs);
	else
		SubmitLink(formname, linkid);
}

function AjaxGet(pageRef, staticPage, ajaxPage, containerid) {
  var ajaxPageRef = pageRef.replace(staticPage, ajaxPage);
  if(ajaxpage(ajaxPageRef, containerid, 'GET')) {
    IVWPixel();
  	ajaxpageaction = ajaxPageRef;
  	isajaxpostback = true;
  	return false;	// return false to avoid a page reload
  }
}

function AjaxPost(containerid, params) {
  if(ajaxpage(ajaxpageaction, containerid, 'POST', params)) {
  	return false;	// return false to avoid a page reload
  }
}



if (document.domain.indexOf("medienhaus.at") > 0) document.domain = "medienhaus.at";
//prototype object:Tab
function Tab(strTabID, strTabName, nodeContent) {
	//properties & defaults
	this.strTabName 			= "New Tab";
	this.nodeContent			= null;
	this.strTabID				= null;

	
	//set properties
	if (nodeContent)
		this.nodeContent 	= nodeContent;
	if (strTabName)
		this.strTabName 	= strTabName;
	if (strTabID)
		this.strTabID 		= strTabID;
}


//prototype object: TabBox
function PortalTabBox(strContainerNodeID, iBoxHeight, boolCycle, iCyclePeriod) {
	
	//properties & defaults
	this.nodeContainer 		= null;
	this.nodeContent		= document.createElement("div");
	this.strID				= "TabBox";
	this.arrTabs			= new Array();
	this.strActiveTabID		= null;
	this.iBoxHeight			= 200;
	this.boolCycle			= false;
	this.iCyclePeriod		= 5000;
	this.strHeadlineMarkup	= null;
	this.boolAdminMode      = false;
	
	//set properties
	this.iBoxHeight			= iBoxHeight;
	this.boolCycle			= boolCycle;
	this.iCyclePeriod		= iCyclePeriod;
	if (document.getElementById(strContainerNodeID))
		this.nodeContainer = document.getElementById(strContainerNodeID);
	
}

	//method for TabBox: add a tab
	PortalTabBox.prototype.AddTab = function(strTabID, strTabName, ContentNode) {
		//alert(ContentNode.innerHTML);
		var newtab = new Tab (strTabID, strTabName, ContentNode);
		this.arrTabs.push(newtab); 
	};
	
	//method for TabBox: set the active tab
	PortalTabBox.prototype.SetActiveTab = function(strTabID) {
		//alert(strTabID);
		this.strActiveTabID = strTabID;
	};
	
	//method for TabBox: change active tab
	PortalTabBox.prototype.ChangeTab = function(strTabID) {
		//alert (strTabID);
		this.SetActiveTab(strTabID);
		this.Render();
		return false;
	};
	
	//method for TabBox: toggle cycling through active tabs
	PortalTabBox.prototype.ToggleCycleTabs = function (boolActive) {
		this.boolCycle = boolActive;
	};
	
	//method for TabBox: go to next Tab 
	PortalTabBox.prototype.GoToNextTab = function () {
		if (this.boolCycle) {
			//find next tab
			var strNextTabID;
			for (var t=0; t<this.arrTabs.length; t++) {
				if (this.arrTabs[t].strTabID == this.strActiveTabID) {
					if (t==(this.arrTabs.length-1)) {
						strNextTabID = this.arrTabs[0].strTabID;
						break;
					}
					if (t<(this.arrTabs.length-1)) {
						strNextTabID = this.arrTabs[t+1].strTabID;
					}
				}   
			}
			this.ChangeTab(strNextTabID);
		}
	};
	
	//method for getting all tabs
	PortalTabBox.prototype.GetContent	= function() {
		if (this.nodeContainer) {
		    	        	   
		    if (this.nodeContainer.innerHTML.match(/portlet/)) this.boolAdminMode = true;
			
			if (!this.boolAdminMode) {	
				
		        //fetch the title of the box, if there is one
		        // - get the first occurence of a h2 node in all child nodes
        		
		        var nodeTitle =  this.FindFirstChild(this.nodeContainer, "H2", "DIV");
		        if (nodeTitle) {
			        this.AddHeadline(nodeTitle.innerHTML);
			        //alert(nodeTitle.innerHTML);
		        }
		        var nodeContentContainer = this.FindFirstChild(this.nodeContainer, "DIV");
        		
        		
		        if (nodeContentContainer && nodeContentContainer.hasChildNodes() ) {
			        //get each h3 - div pair inside... (hui...)
			        var nodeChild = nodeContentContainer.firstChild;
			        var iTabNum = 0;
			        do {
				        var nodeTabTitle = this.FindFirstSilbling(nodeChild, "H3", "DIV");
				        if (nodeTabTitle) {
					        //alert(nodeTabTitle.innerHTML);
					        nodeChild = nodeTabTitle.nextSibling;
					        var nodeTabContent = this.FindFirstSilbling(nodeChild, "DIV", "H3");
					        if (nodeTabContent) {
						        //strTabID, strTabName, strContentProviderNode
						        this.AddTab("Tab" + iTabNum, nodeTabTitle.innerHTML, nodeTabContent.cloneNode(true));
						        //alert(nodeTabContent.innerHTML);
						        iTabNum++;
						        nodeChild = nodeTabContent.nextSibling;
					        }
				        }
				        else {				
					        nodeChild = nodeChild.nextSibling;
				        }
			        }
			        while (nodeChild);
		        }
		    }
	    }	
	}
	
	//method for adding additional, external tabcontent _without_ rendering the result
	PortalTabBox.prototype.AddExternalTabDelayed = function (strProviderNodeId) {
       var nodeProviderNode = document.getElementById(strProviderNodeId);
       if (nodeProviderNode && nodeProviderNode.hasChildNodes() ) {
            //get each h3 - div pair inside... (hui...)
            var nodeChild = nodeProviderNode.firstChild;
            do {
                var nodeTabTitle = this.FindFirstSilbling(nodeChild, "H3", "DIV");
                if (nodeTabTitle) {
                   //alert(nodeTabTitle.innerHTML);
                   nodeChild = nodeTabTitle.nextSibling;
                   var nodeTabContent = this.FindFirstSilbling(nodeChild, "DIV", "H3");
                   if (nodeTabContent) {
	                   //strTabID, strTabName, strContentProviderNode
	                   this.AddTab(strProviderNodeId, nodeTabTitle.innerHTML, nodeTabContent.cloneNode(true));
	                   //alert(nodeTabContent.innerHTML);
	                   nodeChild = nodeTabContent.nextSibling;
                   }
                }
                else {				
                   nodeChild = nodeChild.nextSibling;
                }
            }
            while (nodeChild);
            
            //clean up and remove all childs in nodeProviderNode
		    while (nodeProviderNode.firstChild)
			    nodeProviderNode.removeChild(nodeProviderNode.firstChild)
       }    
	}
	
	//method for adding additional, external tabcontent and rendering the result
	PortalTabBox.prototype.AddExternalTab = function (strProviderNodeId) {
	    this.AddExternalTabDelayed(strProviderNodeId);
	    this.Render();
	}
	
	
	
	
	//method for finding the first child node with a certain node name while not passing a node which is not allowed
	PortalTabBox.prototype.FindFirstChild = function (nodeParent, strNodeName, strNodeNameNotAllowed) {
		var nodeChild = nodeParent.firstChild;
		do {
			//passing a node which is not allowed?
			if (strNodeNameNotAllowed)
				if (nodeChild && nodeChild.nodeName == strNodeNameNotAllowed) return null;
			if (nodeChild && nodeChild.nodeName == strNodeName) return nodeChild;
			nodeChild = nodeChild.nextSibling;
		}
		while (nodeChild);
		return null;
	}
	
	//method for finding the first silbling node with a certain node name while not passing a node which is not allowed
	PortalTabBox.prototype.FindFirstSilbling = function (nodeSilbling, strNodeName, strNodeNameNotAllowed) {
		var nodeSilbling = nodeSilbling;
		do {
			if (strNodeNameNotAllowed)
				if (nodeSilbling && nodeSilbling.nodeName == strNodeNameNotAllowed) return null;
			if (nodeSilbling && nodeSilbling.nodeName == strNodeName) return nodeSilbling;
			nodeSilbling = nodeSilbling.nextSibling;
		}
		while (nodeSilbling);
		return null;
	}
	
	
	//method for drawing the content
	PortalTabBox.prototype.DrawContent = function(nodeContentTarget, nodeContentProvider) {
		//alert(this.nodeContentProvider.innerHTML);
		//clean up first...
		while (nodeContentTarget.firstChild)
			nodeContentTarget.removeChild(nodeContentTarget.firstChild)
		//append the contentprovider node to the content node
		if (nodeContentProvider) {
			//alert(nodeContentProvider.innerHTML);
			var newContent = nodeContentProvider.cloneNode(true);
			newContent.removeAttribute("style");
			newContent.visibility = "visible";
			nodeContentTarget.appendChild(newContent);
		}
	}
	
	
	//method for adding a headline to the box (markup allowed)
	PortalTabBox.prototype.AddHeadline = function (strHeadlineMarkup) {
		if (strHeadlineMarkup) this.strHeadlineMarkup = strHeadlineMarkup;
	};
	
	
	
	
	
	
	
	//method for TabBox: render the box
	PortalTabBox.prototype.Render = function(boolUpdate) {
		//override in subclasses
	};
	
	

/////////1 COLUMN 115px//////////////////
//inherits TabBox	
function TabBox1Col115(strContainerNodeID, iContentHeight, boolCycle, iCyclePeriod) {
	//pass the parameters to the ancestors constructor
	this.constructor(strContainerNodeID, iContentHeight, boolCycle, iCyclePeriod);
	//fetch the content
	this.GetContent();
}	
//do the inheritance
TabBox1Col115.prototype = new PortalTabBox();

    
    //method for TabBox1Col: render the box
	TabBox1Col115.prototype.Render = function() {
		if (this.nodeContainer && !this.boolAdminMode) {
		    //create main elements
		    var TabBox 			= this;
		    var Box1Col 		= document.createElement("div");
		    var PaneTop			= document.createElement("div");
		    var PaneBottom		= document.createElement("div");
    		
		    //assign css classes;
		    Box1Col.className 			= "Dotcom_TabBox1Col115";
		    PaneTop.className 			= "PaneTop";
		    PaneBottom.className 		= "PaneBottom";
    		
		    //clean up and remove all childs in container
		    while (this.nodeContainer.firstChild)
			    this.nodeContainer.removeChild(this.nodeContainer.firstChild)
    			
		    //iterate over tabs...
		    if (this.arrTabs.length > 0) {
    			
    			if (this.strActiveTabID	== null) this.strActiveTabID = this.arrTabs[0].strTabID;
    			
			    var boolActiverow				= false;
			    var Headline					= document.createElement("h4");
				    Headline.className			= "Dotcom_TabBox";
			    var ULTop 						= document.createElement("ul");
				    ULTop.className				= "Dotcom_TabBox Dotcom_TabBox1Col115TopLinks";
			    var ULBottom					= document.createElement("ul");
				    ULBottom.className			= "Dotcom_TabBox Dotcom_TabBox1Col115BottomLinks";
			    var nodeContentProvider;
			    this.nodeContent.className		= "Dotcom_TabBox1Col115Content";
    			
			    var iNextElement				= 0;
			    var iContentHeight				= this.iBoxHeight
    			
			    //calculate content height //36
			    iContentHeight	= this.iBoxHeight - ( (this.arrTabs.length * 30) + 17 );
    					
			    //headline, if set...
			    if (this.strHeadlineMarkup && this.strHeadlineMarkup != "") {
				    iContentHeight	-= 19;
				    Headline.innerHTML = this.strHeadlineMarkup;
				    PaneBottom.appendChild(Headline);
			    }
			    if (iContentHeight>0) this.nodeContent.style.height	= iContentHeight + "px";
			    PaneBottom.style.height = (this.iBoxHeight - 4) + "px";
    			
			    //top tabs
			    for(var t = 0; t< this.arrTabs.length; t++) {
				    var li				= document.createElement("li");
				    var a				= document.createElement("a");
				    var strTabName 		= TabBox.arrTabs[t].strTabName;
				    var strTabID		= TabBox.arrTabs[t].strTabID;
				    var OnClickEvent	= function () { TabBox.ToggleCycleTabs(false);  TabBox.ChangeTab(this.id); return false; };
    				
				    if (strTabID == this.strActiveTabID) {
					    boolActiverow		= true;
					    nodeContentProvider = this.arrTabs[t].nodeContent;
					    li.className += " Active";
				    }
				    a.href 		= "#";
				    a.id 		= strTabID;
				    a.onclick 	= OnClickEvent;
				    a.appendChild(document.createTextNode(strTabName));
				    li.appendChild(a);
				    ULTop.appendChild(li);
    				
				    //leave iteration if active tab is in this row
				    if (boolActiverow) {
					    iNextElement = t + 1;
					    break;
				    }
			    }
    			
			    PaneBottom.appendChild(ULTop);
    			
			    //do only if there is a active tab
			    if (boolActiverow) {
    				
				    this.DrawContent(this.nodeContent, nodeContentProvider);
				    PaneBottom.appendChild(this.nodeContent);
    				
				    if (iNextElement<this.arrTabs.length) {
						    PaneBottom.appendChild(ULBottom);
				    }
    				
				    //bottom tabs
				    for (t = iNextElement; t< this.arrTabs.length; t++) {
					    var li				= document.createElement("li");
					    var a 				= document.createElement("a");
					    var strTabName  	= TabBox.arrTabs[t].strTabName;
					    var strTabID		= TabBox.arrTabs[t].strTabID;
					    var OnClickEvent	= function () { TabBox.ToggleCycleTabs(false); TabBox.ChangeTab(this.id); return false; };
    					
					    a.href 		= "#";
					    a.id 		= strTabID;
					    a.onclick 	= OnClickEvent;
					    a.appendChild(document.createTextNode(strTabName));
					    li.appendChild(a);
					    ULBottom.appendChild(li);
				    }
    				
			    }
		    }
		    //append pane to box node
		    Box1Col.appendChild(PaneTop);
		    Box1Col.appendChild(PaneBottom);
    		
		    //put everything in the container node
		    this.nodeContainer.appendChild(Box1Col);
		    //set timeout for cycling through tabs
		    if (this.boolCycle && this.arrTabs.length>0) window.setTimeout(function () {TabBox.GoToNextTab() }, TabBox.iCyclePeriod);
		}
	}	
    

/////////1 COLUMN 150px//////////////////
//inherits TabBox	
function TabBox1Col150(strContainerNodeID, iContentHeight, boolCycle, iCyclePeriod) {
	//pass the parameters to the ancestors constructor
	this.constructor(strContainerNodeID, iContentHeight, boolCycle, iCyclePeriod);
	//fetch the content
	this.GetContent();
}	
//do the inheritance
TabBox1Col150.prototype = new PortalTabBox();

    
    //method for TabBox1Col: render the box
	TabBox1Col150.prototype.Render = function() {
		if (this.nodeContainer && !this.boolAdminMode) {
		    //create main elements
		    var TabBox 			= this;
		    var Box1Col 		= document.createElement("div");
		    var PaneTop			= document.createElement("div");
		    var PaneBottom		= document.createElement("div");
    		
		    //assign css classes;
		    Box1Col.className 			= "Dotcom_TabBox1Col150";
		    PaneTop.className 			= "PaneTop";
		    PaneBottom.className 		= "PaneBottom";
    		
		    //clean up and remove all childs in container
		    while (this.nodeContainer.firstChild)
			    this.nodeContainer.removeChild(this.nodeContainer.firstChild)
    			
		    //iterate over tabs...
		    if (this.arrTabs.length > 0) {
    			
    			if (this.strActiveTabID	== null) this.strActiveTabID = this.arrTabs[0].strTabID;
    			
			    var boolActiverow				= false;
			    var Headline					= document.createElement("h4");
				    Headline.className			= "Dotcom_TabBox";
			    var ULTop 						= document.createElement("ul");
				    ULTop.className				= "Dotcom_TabBox Dotcom_TabBox1Col150TopLinks";
			    var ULBottom					= document.createElement("ul");
				    ULBottom.className			= "Dotcom_TabBox Dotcom_TabBox1Col150BottomLinks";
			    var nodeContentProvider;
			    this.nodeContent.className		= "Dotcom_TabBox1Col150Content";
    			
			    var iNextElement				= 0;
			    var iContentHeight				= this.iBoxHeight
    			
			    //calculate content height //36
			    iContentHeight	= this.iBoxHeight - ( (this.arrTabs.length * 30) + 17 );
    					
			    //headline, if set...
			    if (this.strHeadlineMarkup && this.strHeadlineMarkup != "") {
				    iContentHeight	-= 19;
				    Headline.innerHTML = this.strHeadlineMarkup;
				    PaneBottom.appendChild(Headline);
			    }
			    if (iContentHeight>0) this.nodeContent.style.height	= iContentHeight + "px";
			    PaneBottom.style.height = (this.iBoxHeight - 4) + "px";
    			
			    //top tabs
			    for(var t = 0; t< this.arrTabs.length; t++) {
				    var li				= document.createElement("li");
				    var a				= document.createElement("a");
				    var strTabName 		= TabBox.arrTabs[t].strTabName;
				    var strTabID		= TabBox.arrTabs[t].strTabID;
				    var OnClickEvent	= function () { TabBox.ToggleCycleTabs(false);  TabBox.ChangeTab(this.id); return false; };
    				
				    if (strTabID == this.strActiveTabID) {
					    boolActiverow		= true;
					    nodeContentProvider = this.arrTabs[t].nodeContent;
					    li.className += " Active";
				    }
				    a.href 		= "#";
				    a.id 		= strTabID;
				    a.onclick 	= OnClickEvent;
				    a.appendChild(document.createTextNode(strTabName));
				    li.appendChild(a);
				    ULTop.appendChild(li);
    				
				    //leave iteration if active tab is in this row
				    if (boolActiverow) {
					    iNextElement = t + 1;
					    break;
				    }
			    }
    			
			    PaneBottom.appendChild(ULTop);
    			
			    //do only if there is a active tab
			    if (boolActiverow) {
    				
				    this.DrawContent(this.nodeContent, nodeContentProvider);
				    PaneBottom.appendChild(this.nodeContent);
    				
				    if (iNextElement<this.arrTabs.length) {
						    PaneBottom.appendChild(ULBottom);
				    }
    				
				    //bottom tabs
				    for (t = iNextElement; t< this.arrTabs.length; t++) {
					    var li				= document.createElement("li");
					    var a 				= document.createElement("a");
					    var strTabName  	= TabBox.arrTabs[t].strTabName;
					    var strTabID		= TabBox.arrTabs[t].strTabID;
					    var OnClickEvent	= function () { TabBox.ToggleCycleTabs(false); TabBox.ChangeTab(this.id); return false; };
    					
					    a.href 		= "#";
					    a.id 		= strTabID;
					    a.onclick 	= OnClickEvent;
					    a.appendChild(document.createTextNode(strTabName));
					    li.appendChild(a);
					    ULBottom.appendChild(li);
				    }
    				
			    }
		    }
		    //append pane to box node
		    Box1Col.appendChild(PaneTop);
		    Box1Col.appendChild(PaneBottom);
    		
		    //put everything in the container node
		    this.nodeContainer.appendChild(Box1Col);
		    //set timeout for cycling through tabs
		    if (this.boolCycle && this.arrTabs.length>0) window.setTimeout(function () {TabBox.GoToNextTab() }, TabBox.iCyclePeriod);
		}
	}	
    

	
/////////1 COLUMN//////////////////
//inherits TabBox	
function TabBox1Col(strContainerNodeID, iContentHeight, boolCycle, iCyclePeriod) {
	//pass the parameters to the ancestors constructor
	this.constructor(strContainerNodeID, iContentHeight, boolCycle, iCyclePeriod);
	//fetch the content
	this.GetContent();
}	
//do the inheritance
TabBox1Col.prototype = new PortalTabBox();

	//method for TabBox1Col: render the box
	TabBox1Col.prototype.Render = function() {
		if (this.nodeContainer && !this.boolAdminMode) {
		    //create main elements
		    var TabBox 			= this;
		    var Box1Col 		= document.createElement("div");
		    var PaneTop			= document.createElement("div");
		    var PaneBottom		= document.createElement("div");
    		
		    //assign css classes;
		    Box1Col.className 			= "Dotcom_TabBox1Col";
		    PaneTop.className 			= "PaneTop";
		    PaneBottom.className 		= "PaneBottom";
    		
		    //clean up and remove all childs in container
		    while (this.nodeContainer.firstChild)
			    this.nodeContainer.removeChild(this.nodeContainer.firstChild)
    			
		    //iterate over tabs...
		    if (this.arrTabs.length > 0) {
    			
    			if (this.strActiveTabID	== null) this.strActiveTabID = this.arrTabs[0].strTabID;
    			
			    var boolActiverow				= false;
			    var Headline					= document.createElement("h4");
				    Headline.className			= "Dotcom_TabBox";
			    var ULTop 						= document.createElement("ul");
				    ULTop.className				= "Dotcom_TabBox Dotcom_TabBox1ColTopLinks";
			    var ULBottom					= document.createElement("ul");
				    ULBottom.className			= "Dotcom_TabBox Dotcom_TabBox1ColBottomLinks";
			    var nodeContentProvider;
			    this.nodeContent.className		= "Dotcom_TabBox1ColContent";
    			
			    var iNextElement				= 0;
			    var iContentHeight				= this.iBoxHeight
    			
			    //calculate content height //36
			    iContentHeight	= this.iBoxHeight - ( (this.arrTabs.length * 30) + 17 );
    					
			    //headline, if set...
			    if (this.strHeadlineMarkup && this.strHeadlineMarkup != "") {
				    iContentHeight	-= 19;
				    Headline.innerHTML = this.strHeadlineMarkup;
				    PaneBottom.appendChild(Headline);
			    }
			    if (iContentHeight>0) this.nodeContent.style.height	= iContentHeight + "px";
			    PaneBottom.style.height = (this.iBoxHeight - 4) + "px";
    			
			    //top tabs
			    for(var t = 0; t< this.arrTabs.length; t++) {
				    var li				= document.createElement("li");
				    var a				= document.createElement("a");
				    var strTabName 		= TabBox.arrTabs[t].strTabName;
				    var strTabID		= TabBox.arrTabs[t].strTabID;
				    var OnClickEvent	= function () { TabBox.ToggleCycleTabs(false);  TabBox.ChangeTab(this.id); return false; };
    				
				    if (strTabID == this.strActiveTabID) {
					    boolActiverow		= true;
					    nodeContentProvider = this.arrTabs[t].nodeContent;
					    li.className += " Active";
				    }
				    a.href 		= "#";
				    a.id 		= strTabID;
				    a.onclick 	= OnClickEvent;
				    a.appendChild(document.createTextNode(strTabName));
				    li.appendChild(a);
				    ULTop.appendChild(li);
    				
				    //leave iteration if active tab is in this row
				    if (boolActiverow) {
					    iNextElement = t + 1;
					    break;
				    }
			    }
    			
			    PaneBottom.appendChild(ULTop);
    			
			    //do only if there is a active tab
			    if (boolActiverow) {
    				
				    this.DrawContent(this.nodeContent, nodeContentProvider);
				    PaneBottom.appendChild(this.nodeContent);
    				
				    if (iNextElement<this.arrTabs.length) {
						    PaneBottom.appendChild(ULBottom);
				    }
    				
				    //bottom tabs
				    for (t = iNextElement; t< this.arrTabs.length; t++) {
					    var li				= document.createElement("li");
					    var a 				= document.createElement("a");
					    var strTabName  	= TabBox.arrTabs[t].strTabName;
					    var strTabID		= TabBox.arrTabs[t].strTabID;
					    var OnClickEvent	= function () { TabBox.ToggleCycleTabs(false); TabBox.ChangeTab(this.id); return false; };
    					
					    a.href 		= "#";
					    a.id 		= strTabID;
					    a.onclick 	= OnClickEvent;
					    a.appendChild(document.createTextNode(strTabName));
					    li.appendChild(a);
					    ULBottom.appendChild(li);
				    }
    				
			    }
		    }
		    //append pane to box node
		    Box1Col.appendChild(PaneTop);
		    Box1Col.appendChild(PaneBottom);
    		
		    //put everything in the container node
		    this.nodeContainer.appendChild(Box1Col);
		    //set timeout for cycling through tabs
		    if (this.boolCycle && this.arrTabs.length>0) window.setTimeout(function () {TabBox.GoToNextTab() }, TabBox.iCyclePeriod);
		}
	}	


	
	
/////////2 COLUMNS//////////////////	
//inherits TabBox	
function TabBox2Col(strContainerNodeID, iContentHeight, boolCycle, iCyclePeriod) {
	//pass the parameters to the ancestors constructor
	this.constructor(strContainerNodeID, iContentHeight, boolCycle, iCyclePeriod);
	//fetch the content
	this.GetContent();
}
//do the inheritance
TabBox2Col.prototype = new PortalTabBox();
	
	//method for TabBox2Col: render the box
	TabBox2Col.prototype.Render = function() {
	    
	    if (this.nodeContainer && !this.boolAdminMode) {
	    
		    //create main elements
		    var Box2Col 		= document.createElement("div");
		    var PaneTop			= document.createElement("div");
		    var PaneBottom		= document.createElement("div");
		    var ClearFloat		= document.createElement("br");
    		
		    //assign css classes
		    Box2Col.className 			= "Dotcom_TabBox2Col";
		    PaneTop.className 			= "PaneTop";
		    PaneBottom.className 		= "PaneBottom";
		    ClearFloat.className		= "Clear";
    		
		    //clean up and remove all childs in container
		    while (this.nodeContainer.firstChild)
			    this.nodeContainer.removeChild(this.nodeContainer.firstChild)
    		
		    //iterate over tabs...
		    if (this.arrTabs.length > 0) {
		    
		        if (this.strActiveTabID	== null) this.strActiveTabID = this.arrTabs[0].strTabID;
		    
			    var TabBox 						= this;
			    var col 						= 0;
			    var boolActiverow				= false;
			    var Headline					= document.createElement("h4");
				    Headline.className			= "Dotcom_TabBox";
			    var ULTop 						= document.createElement("ul");
				    ULTop.className				= "Dotcom_TabBox Dotcom_TabBox2ColTopLinks";
			    var ULBottom					= document.createElement("ul");
				    ULBottom.className			= "Dotcom_TabBox Dotcom_TabBox2ColBottomLinks";
			    var nodeContentProvider;
			    var ClearFloatTop				= ClearFloat.cloneNode(false);
			    var ClearFloatBottom			= ClearFloat.cloneNode(false);
			    this.nodeContent.className		= "Dotcom_TabBox2ColContent";
			    var nodeContentFooter			= document.createElement("div");	
				    nodeContentFooter.className = "Dotcom_TabBox2ColContentFooter";
			    var iNextElement				= 0;
			    var iContentHeight				= this.iBoxHeight
    						
			    //calculate content height //
			    iContentHeight	= this.iBoxHeight - ( (Math.ceil(this.arrTabs.length/2) * 30) + 20 );
    					
			    //headline, if set...
			    if (this.strHeadlineMarkup && this.strHeadlineMarkup != "") {
				    iContentHeight	-= 19;
				    Headline.innerHTML = this.strHeadlineMarkup;
				    PaneBottom.appendChild(Headline);
			    }
			    if (iContentHeight>0) this.nodeContent.style.height	= iContentHeight + "px";
			    PaneBottom.style.height = (this.iBoxHeight - 4) + "px";
    			
			    //top tabs
			    for(var t = 0; t< this.arrTabs.length; t++) {
				    var li				= document.createElement("li");
				    var a				= document.createElement("a");
				    var strTabName 		= TabBox.arrTabs[t].strTabName;
				    var strTabID		= TabBox.arrTabs[t].strTabID;
				    var OnClickEvent	= function () { TabBox.ToggleCycleTabs(false);  TabBox.ChangeTab(this.id); return false; };
    				
    				
				    if (col == 1) li.className = "Right";
				    if (strTabID == this.strActiveTabID) {
					    boolActiverow		= true;
					    nodeContentProvider = this.arrTabs[t].nodeContent;
					    li.className += " Active";
					    if (col == 0) this.nodeContent.className += " LeftTab";
					    else this.nodeContent.className += " RightTab";
				    }
				    a.href 		= "#";
				    a.id 		= strTabID;
				    a.onclick 	= OnClickEvent;
				    a.appendChild(document.createTextNode(strTabName));
				    li.appendChild(a);
				    ULTop.appendChild(li);
    				
				    //leave iteration if active tab is in this row
				    if ((col==1 && boolActiverow) || (t==(this.arrTabs.length-1) && boolActiverow)) {
					    iNextElement = t + 1;
					    break;
				    }
				    col = col + 1; if (col>1) col = 0;
			    }
    			
			    PaneBottom.appendChild(ULTop);
			    PaneBottom.appendChild(ClearFloatTop);
    			
			    //do only if there is a active tab
			    if (boolActiverow) {
    				
				    this.DrawContent(this.nodeContent, nodeContentProvider);
				    PaneBottom.appendChild(this.nodeContent);
				    PaneBottom.appendChild(nodeContentFooter);
    				
				    //bottom tabs
				    col = 0;
				    for (t = iNextElement; t< this.arrTabs.length; t++) {
					    var li				= document.createElement("li");
					    var a 				= document.createElement("a");
					    var strTabName  	= TabBox.arrTabs[t].strTabName;
					    var strTabID		= TabBox.arrTabs[t].strTabID;
					    var OnClickEvent	= function () { TabBox.ToggleCycleTabs(false); TabBox.ChangeTab(this.id); return false; };
    					
					    if (col == 1) li.className = "Right";
					    a.href 		= "#";
					    a.id 		= strTabID;
					    a.onclick 	= OnClickEvent;
					    a.appendChild(document.createTextNode(strTabName));
					    li.appendChild(a);
					    ULBottom.appendChild(li);
					    col = col + 1; if (col>1) col = 0;
				    }
				    if (iNextElement<this.arrTabs.length) {
					    PaneBottom.appendChild(ULBottom);
					    PaneBottom.appendChild(ClearFloatBottom);
				    }
			    }
		    }
    		
		    Box2Col.appendChild(PaneTop);
		    Box2Col.appendChild(PaneBottom);
    		
    		
		    //put everything in the container node
		    this.nodeContainer.appendChild(Box2Col);
		    //set timeout for cycling through tabs
		    if (this.boolCycle && this.arrTabs.length>0) window.setTimeout(function () {TabBox.GoToNextTab() }, TabBox.iCyclePeriod);
		}
	}		
	
		

/////////3 COLUMNS//////////////////
//inherits TabBox	
function TabBox3Col(strContainerNodeID, iContentHeight, boolCycle, iCyclePeriod) {
	//pass the parameters to the ancestors constructor
	this.constructor(strContainerNodeID, iContentHeight, boolCycle, iCyclePeriod);
	//fetch the content
	this.GetContent();
}	
//do the inheritance
TabBox3Col.prototype = new PortalTabBox();	


	//method for TabBox3Col: render the box
	TabBox3Col.prototype.Render = function() {
	    
	    if (this.nodeContainer && !this.boolAdminMode) {
	
		    //create main elements
		    var Box3Col 		= document.createElement("div");
		    var PaneTop			= document.createElement("div");
		    var PaneBottom		= document.createElement("div");
		    var ClearFloat		= document.createElement("br");
    		
		    //assign css classes;
		    Box3Col.className 			= "Dotcom_TabBox3Col";
		    PaneTop.className 			= "PaneTop";
		    PaneBottom.className 		= "PaneBottom";
		    ClearFloat.className		= "Clear";
    		
		    //clean up and remove all childs in container
		    while (this.nodeContainer.firstChild)
			    this.nodeContainer.removeChild(this.nodeContainer.firstChild)
    		
		    //iterate over tabs...
		    if (this.arrTabs.length > 0) {
		        
		        if (this.strActiveTabID	== null) this.strActiveTabID = this.arrTabs[0].strTabID;
		    
			    var TabBox 						= this;
			    var col 						= 0;
			    var boolActiverow				= false;
			    var Headline					= document.createElement("h4");
				    Headline.className			= "Dotcom_TabBox";
			    var ULTop 						= document.createElement("ul");
				    ULTop.className				= "Dotcom_TabBox Dotcom_TabBox3ColTopLinks";
			    var ULBottom					= document.createElement("ul");
				    ULBottom.className			= "Dotcom_TabBox Dotcom_TabBox3ColBottomLinks";
			    var nodeContentProvider;
			    var ClearFloatTop				= ClearFloat.cloneNode(false);
			    var ClearFloatBottom			= ClearFloat.cloneNode(false);
			    this.nodeContent.className		= "Dotcom_TabBox3ColContent";
			    var nodeContentHeader			= document.createElement("div");	
			    nodeContentHeader.className 	= "Dotcom_TabBox3ColContentTop";
			    var nodeContentFooter			= document.createElement("div");	
				    nodeContentFooter.className = "Dotcom_TabBox3ColContentBot";
			    var iContentHeight				= this.iBoxHeight
    				
			    //calculate content height //36
			    var rows; if (this.arrTabs.length>3) rows = 2; else rows = 1;
			    iContentHeight	= this.iBoxHeight - ( (rows * 30) + 20 );
    					
			    //headline, if set...
			    if (this.strHeadlineMarkup && this.strHeadlineMarkup != "") {
				    iContentHeight	-= 19;
				    Headline.innerHTML = this.strHeadlineMarkup;
				    PaneBottom.appendChild(Headline);
			    }
			    if (iContentHeight>0) this.nodeContent.style.height	= iContentHeight + "px";
			    //PaneBottom.style.height = (this.iBoxHeight - 4) + "px";
    			
    				
			    //top tabs
			    for(var t = 0; (t< this.arrTabs.length && t<3); t++) {
				    var li				= document.createElement("li");
				    var a				= document.createElement("a");
				    var strTabName 		= TabBox.arrTabs[t].strTabName;
				    var strTabID		= TabBox.arrTabs[t].strTabID;
				    var OnClickEvent	= function () { TabBox.ToggleCycleTabs(false); TabBox.ChangeTab(this.id); return false; };
    				
				    if (col == 2) li.className += " Right";
				    if (strTabID == this.strActiveTabID) {
					    boolActiverow		= true;
					    nodeContentProvider = this.arrTabs[t].nodeContent;
					    li.className += " Active";
					    if (col == 0) nodeContentHeader.className += "Left";
					    if (col == 1) nodeContentHeader.className += "Mid";
					    if (col == 2) nodeContentHeader.className += "Right";
				    }
    				
				    a.href 		= "#";
				    a.id 		= strTabID;
				    a.onclick 	= OnClickEvent;
				    a.appendChild(document.createTextNode(strTabName));
				    li.appendChild(a);
				    ULTop.appendChild(li);
    				
				    col = col + 1; if (col>2) col = 0;
			    }
    			
			    PaneBottom.appendChild(ULTop);
			    PaneBottom.appendChild(ClearFloatTop);
    			
    			
			    PaneBottom.appendChild(nodeContentHeader);
			    PaneBottom.appendChild(this.nodeContent);
			    PaneBottom.appendChild(nodeContentFooter);
    			
    			
			    //bottom tabs
			    col = 0;
			    for(var t = 3; (t< this.arrTabs.length && t<6); t++) {
				    var li				= document.createElement("li");
				    var a				= document.createElement("a");
				    var strTabName 		= TabBox.arrTabs[t].strTabName;
				    var strTabID		= TabBox.arrTabs[t].strTabID;
				    var OnClickEvent	= function () { TabBox.ToggleCycleTabs(false); TabBox.ChangeTab(this.id); return false; };
    				
				    if (col == 2) li.className += " Right";
				    if (strTabID == this.strActiveTabID) {
					    boolActiverow		= true;
					    nodeContentProvider = this.arrTabs[t].nodeContent;
					    li.className += " Active";
					    if (col == 0) nodeContentFooter.className += "Left";
					    if (col == 1) nodeContentFooter.className += "Mid";
					    if (col == 2) nodeContentFooter.className += "Right";
				    }
    	
				    a.href 		= "#";
				    a.id 		= strTabID;
				    a.onclick 	= OnClickEvent;
				    a.appendChild(document.createTextNode(strTabName));
				    li.appendChild(a);
				    ULBottom.appendChild(li);
    				
				    col = col + 1; if (col>2) col = 0;
			    }
    			
			    if (boolActiverow)
				    this.DrawContent(this.nodeContent, nodeContentProvider);
    						
			    if (this.arrTabs.length > 3) {
				    PaneBottom.appendChild(ULBottom);
				    PaneBottom.appendChild(ClearFloatBottom);			
			    }
    			
		    }
    		
		    //append pane to box node
		    Box3Col.appendChild(PaneTop);
		    Box3Col.appendChild(PaneBottom);
    		
		    //put everything in the container node
		    this.nodeContainer.appendChild(Box3Col);
		    //set timeout for cycling through tabs
		    if (this.boolCycle && this.arrTabs.length>0) window.setTimeout(function () {TabBox.GoToNextTab() }, TabBox.iCyclePeriod);
		}
	}

/*****************************************************************************\

 Javascript "SOAP Client" library

 @version: 1.4 - 2005.12.10
 @author: Matteo Casati, Ihar Voitka - http://www.guru4.net/
 @description: (1) SOAPClientParameters.add() method returns 'this' pointer.
               (2) "_getElementsByTagName" method added for xpath queries.
               (3) "_getXmlHttpPrefix" refactored to "_getXmlHttpProgID" (full 
                   ActiveX ProgID).
               
 @version: 1.3 - 2005.12.06
 @author: Matteo Casati - http://www.guru4.net/
 @description: callback function now receives (as second - optional - parameter) 
               the SOAP response too. Thanks to Ihar Voitka.
               
 @version: 1.2 - 2005.12.02
 @author: Matteo Casati - http://www.guru4.net/
 @description: (1) fixed update in v. 1.1 for no string params.
               (2) the "_loadWsdl" method has been updated to fix a bug when 
               the wsdl is cached and the call is sync. Thanks to Linh Hoang.
               
 @version: 1.1 - 2005.11.11
 @author: Matteo Casati - http://www.guru4.net/
 @description: the SOAPClientParameters.toXML method has been updated to allow
               special characters ("<", ">" and "&"). Thanks to Linh Hoang.

 @version: 1.0 - 2005.09.08
 @author: Matteo Casati - http://www.guru4.net/
 @notes: first release.

\*****************************************************************************/
if (document.domain.indexOf("medienhaus.at") > 0) document.domain = "medienhaus.at";

function SOAPClientParameters()
{
	var _pl = new Array();
	this.add = function(name, value) 
	{
		_pl[name] = value; 
		return this; 
	}
	this.toXml = function()
	{
		var xml = "";
		for(var p in _pl)
		{
			if(typeof(_pl[p]) != "function")
				xml += "<" + p + ">" + _pl[p].toString().replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;") + "</" + p + ">";
		}
		return xml;	
	}
	this.toQueryString = function()
	{
	    var querystring = "";
	    var c = 0;
	    var s = 0;
	    for(var p in _pl)
	    {
	        if(typeof(_pl[p]) != "function") {
	            if (s==0) querystring += "?" + p.toString() + "=" + escape(_pl[p].toString());
	            else  querystring += "&" + p.toString() + "=" + escape(_pl[p].toString());
	            s++;
	        }
	        c++;
	    }
	    return querystring;
	}
}

function SOAPClient() {}

SOAPClient.invoke = function(soap, url, method, parameters, async, callback)
{
    if (soap) {
	    if(async)
		    SOAPClient._loadWsdl(url, method, parameters, async, callback);
	    else
		    return SOAPClient._loadWsdl(url, method, parameters, async, callback);
	}
	else {
	    if(async)
		    SOAPClient._sendGetRequest(url, method, parameters, async, callback);
	    else
		    return SOAPClient._sendGetRequest(url, method, parameters, async, callback);
	}
}

// private: wsdl cache
SOAPClient_cacheWsdl = new Array();

// private: invoke async
SOAPClient._loadWsdl = function(url, method, parameters, async, callback)
{
	// load from cache?
	var wsdl = SOAPClient_cacheWsdl[url];
	if(wsdl + "" != "" && wsdl + "" != "undefined")
		return SOAPClient._sendSoapRequest(url, method, parameters, async, callback, wsdl);
	// get wsdl
	var xmlHttp = SOAPClient._getXmlHttp();
	xmlHttp.open("GET", url + "?wsdl", async);
	if(async) 
	{
		xmlHttp.onreadystatechange = function() 
		{
			if(xmlHttp.readyState == 4)
				SOAPClient._onLoadWsdl(url, method, parameters, async, callback, xmlHttp);
		}
	}
	xmlHttp.send(null);
	if (!async)
		return SOAPClient._onLoadWsdl(url, method, parameters, async, callback, xmlHttp);
}
SOAPClient._onLoadWsdl = function(url, method, parameters, async, callback, req)
{
	var wsdl = req.responseXML;
	SOAPClient_cacheWsdl[url] = wsdl;	// save a copy in cache
	return SOAPClient._sendSoapRequest(url, method, parameters, async, callback, wsdl);
}

SOAPClient._sendGetRequest = function(url, method, parameters, async, callback)
{
    var xmlHttp = SOAPClient._getXmlHttp();
    xmlHttp.open("GET", url + "/" + method + parameters.toQueryString(), async);
    xmlHttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    if(async) 
	{
	    xmlHttp.onreadystatechange = function() 
		{
			if(xmlHttp.readyState == 4)
				SOAPClient._onSendGetRequest(method, async, callback, xmlHttp);
		}
	}
	xmlHttp.send(null);
	if (!async)
		return SOAPClient._onSendGetRequest(method, async, callback, xmlHttp);
}

SOAPClient._onSendGetRequest = function(method, async, callback, req)
{
    var returnXml;
    var doc = document.createElement("div");
    
    try {
        
        doc.innerHTML = req.responseText;
        returnXml  = doc;
    }
    catch(e) {
        //alert("Fehler Fox-Zweig: " + e.description);
    }
    
    try {
    
        if (typeof(req.responseXML.firstChild) != "undefined")
            returnXml = req.responseXML;
    }
    catch(e) {
        //alert("Fehler IE-Zweig: " + e.description);
    }

	if (callback)
	    callback(returnXml);
	
	if (!async)
	    return returnXml;

}


SOAPClient._sendSoapRequest = function(url, method, parameters, async, callback, wsdl)
{
	// get namespace
	var ns = (wsdl.documentElement.attributes["targetNamespace"] + "" == "undefined") ? wsdl.documentElement.attributes.getNamedItem("targetNamespace").nodeValue : wsdl.documentElement.attributes["targetNamespace"].value;
	// build SOAP request
	var sr = 
				"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
				"<soap:Envelope " +
				"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
				"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
				"xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
				"<soap:Body>" +
				"<" + method + " xmlns=\"" + ns + "\">" +
				parameters.toXml() +
				"</" + method + "></soap:Body></soap:Envelope>";
	// send request
	var xmlHttp = SOAPClient._getXmlHttp();
	xmlHttp.open("POST", url, async);
	var soapaction = ((ns.lastIndexOf("/") != ns.length - 1) ? ns + "/" : ns) + method;
	xmlHttp.setRequestHeader("SOAPAction", soapaction);
	xmlHttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
	if(async) 
	{
		xmlHttp.onreadystatechange = function() 
		{
			if(xmlHttp.readyState == 4)
				SOAPClient._onSendSoapRequest(method, async, callback, wsdl, xmlHttp);
		}
	}
	xmlHttp.send(sr);
	if (!async)
		return SOAPClient._onSendSoapRequest(method, async, callback, wsdl, xmlHttp);
}
SOAPClient._onSendSoapRequest = function(method, async, callback, wsdl, req)
{
	var o = null;
	var nd = SOAPClient._getElementsByTagName(req.responseXML, method + "Result");
	if(nd.length == 0)
	{
		if(req.responseXML.getElementsByTagName("faultcode").length > 0)
			throw new Error(500, req.responseXML.getElementsByTagName("faultstring")[0].childNodes[0].nodeValue);
	}
	else
		o = SOAPClient._soapresult2object(nd[0], wsdl);
	if(callback)
		callback(o, req.responseXML);
	if(!async)
		return o;		
}

// private: utils
SOAPClient._getElementsByTagName = function(document, tagName)
{
	try
	{
		// trying to get node omitting any namespaces (latest versions of MSXML.XMLDocument)
		return document.selectNodes(".//*[local-name()=\""+ tagName +"\"]");
	}
	catch (ex) {}
	// old XML parser support
	return document.getElementsByTagName(tagName);
}

SOAPClient._soapresult2object = function(node, wsdl)
{
	return SOAPClient._node2object(node, wsdl);
}
SOAPClient._node2object = function(node, wsdl)
{
	// null node
	if(node == null)
		return null;
	// text node
	if(node.nodeType == 3 || node.nodeType == 4)
		return SOAPClient._extractValue(node, wsdl);
	// leaf node
	if (node.childNodes.length == 1 && (node.childNodes[0].nodeType == 3 || node.childNodes[0].nodeType == 4))
		return SOAPClient._node2object(node.childNodes[0], wsdl);
	var isarray = SOAPClient._getTypeFromWsdl(node.nodeName, wsdl).toLowerCase().indexOf("arrayof") != -1;
	// object node
	if(!isarray)
	{
		var obj = null;
		if(node.hasChildNodes())
			obj = new Object();
		for(var i = 0; i < node.childNodes.length; i++)
		{
			var p = SOAPClient._node2object(node.childNodes[i], wsdl);
			obj[node.childNodes[i].nodeName] = p;
		}
		return obj;
	}
	// list node
	else
	{
		// create node ref
		var l = new Array();
		for(var i = 0; i < node.childNodes.length; i++)
			l[l.length] = SOAPClient._node2object(node.childNodes[i], wsdl);
		return l;
	}
	return null;
}
SOAPClient._extractValue = function(node, wsdl)
{
	var value = node.nodeValue;
	switch(SOAPClient._getTypeFromWsdl(node.parentNode.nodeName, wsdl).toLowerCase())
	{
		default:
		case "s:string":			
			return (value != null) ? value + "" : "";
		case "s:boolean":
			return value+"" == "true";
		case "s:int":
		case "s:long":
			return (value != null) ? parseInt(value + "", 10) : 0;
		case "s:double":
			return (value != null) ? parseFloat(value + "") : 0;
		case "s:datetime":
			if(value == null)
				return null;
			else
			{
				value = value + "";
				value = value.substring(0, value.lastIndexOf("."));
				value = value.replace(/T/gi," ");
				value = value.replace(/-/gi,"/");
				var d = new Date();
				d.setTime(Date.parse(value));										
				return d;				
			}
	}
}
SOAPClient._getTypeFromWsdl = function(elementname, wsdl)
{
	var ell = wsdl.getElementsByTagName("s:element");	// IE
	if(ell.length == 0)
		ell = wsdl.getElementsByTagName("element");	// MOZ
	for(var i = 0; i < ell.length; i++)
	{
		if(ell[i].attributes["name"] + "" == "undefined")	// IE
		{
			if(ell[i].attributes.getNamedItem("name") != null && ell[i].attributes.getNamedItem("name").nodeValue == elementname && ell[i].attributes.getNamedItem("type") != null) 
				return ell[i].attributes.getNamedItem("type").nodeValue;
		}	
		else // MOZ
		{
			if(ell[i].attributes["name"] != null && ell[i].attributes["name"].value == elementname && ell[i].attributes["type"] != null)
				return ell[i].attributes["type"].value;
		}
	}
	return "";
}
// private: xmlhttp factory
SOAPClient._getXmlHttp = function() 
{
	try
	{
		if(window.XMLHttpRequest) 
		{
			var req = new XMLHttpRequest();
			// some versions of Moz do not support the readyState property and the onreadystate event so we patch it!
			if(req.readyState == null) 
			{
				req.readyState = 1;
				req.addEventListener("load", 
									function() 
									{
										req.readyState = 4;
										if(typeof req.onreadystatechange == "function")
											req.onreadystatechange();
									},
									false);
			}
			return req;
		}
		if(window.ActiveXObject) 
			return new ActiveXObject(SOAPClient._getXmlHttpProgID());
	}
	catch (ex) {}
	throw new Error("Your browser does not support XmlHttp objects");
}
SOAPClient._getXmlHttpProgID = function()
{
	if(SOAPClient._getXmlHttpProgID.progid)
		return SOAPClient._getXmlHttpProgID.progid;
	var progids = ["Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
	var o;
	for(var i = 0; i < progids.length; i++)
	{
		try
		{
			o = new ActiveXObject(progids[i]);
			return SOAPClient._getXmlHttpProgID.progid = progids[i];
		}
		catch (ex) {};
	}
	throw new Error("Could not find an installed XML parser");
}

if (document.domain.indexOf("medienhaus.at") > 0) document.domain = "medienhaus.at";

MainNavigationCommon = new Object();
MainNavigationCommon.strSSOErrorMessage 			= "Fehler: Benutzername oder Passwort falsch";
MainNavigationCommon.strAsHomepage1 				= "VOL als";
MainNavigationCommon.strAsHomepage2 				= "Startseite";
MainNavigationCommon.strLogin						= "Anmelden";
MainNavigationCommon.strLogout						= "Abmelden";
MainNavigationCommon.strRegister					= "Registrieren";
MainNavigationCommon.strOr							= "";

MainNavigationCommon.strRegisterUrl					= "http://freunde.vol.at/register.html";
MainNavigationCommon.strLoginUrl					= "http://vol.at/engine.aspx?page=login";
MainNavigationCommon.strUNameFieldName				= "SSOUserName";
MainNavigationCommon.strPWFieldName					= "SSOPassword";
MainNavigationCommon.strUNameValue					= "Benutzername";
MainNavigationCommon.strPWValue						= "Passwort";
MainNavigationCommon.strProfileUrl					= "http://freunde.vol.at/###username###/";
MainNavigationCommon.strSSOWebServiceUrl			= "/snpeservice.asmx";
MainNavigationCommon.strSSOWebServiceAuthMethod		= "AuthenticateAsObjectAndLogin";
MainNavigationCommon.strSSOWebServiceLogoutMethod	= "Logout";				

function PortalUser(strUserName, strPasswordHash) {
	//properties
	this.strUserName 		= null;
	this.strPasswordHash 	= null;
		
	//set given values
	if (strUserName 	&& strUserName != "") 		this.strUserName 		= strUserName;
	if (strPasswordHash && strPasswordHash != "") 	this.strPasswordHash 	= strPasswordHash;
	
}

function MainNavigationBar () {
	//properties
	this.ULNavigation 				= null;
	this.strActiveNodeID1			= null;
	this.nodeActive                 = null;
	this.nodeHover                  = null;
	this.Switch                     = null;
	this.strActiveNodeID2			= null;
	this.User						= null;
		
	this.strRegisterUrl				= MainNavigationCommon.strRegisterUrl;
	this.strLoginUrl				= MainNavigationCommon.strLoginUrl;
	this.strLogoutUrl				= null;
	this.strOverrideLoginUrl		= null; //this is an extra property so we can see if there is an override
		
	this.strFormAction				= null;
	this.strUNameFieldName			= MainNavigationCommon.strUNameFieldName;
	this.strPWFieldName				= MainNavigationCommon.strPWFieldName;
	this.strProfileUrl				= MainNavigationCommon.strProfileUrl;
	this.boolShowLogin              = true; //sets wether the login-stuff is visible or not
	
	//try to fetch user info
	this.User =  this._ReadUserCookie();
}

	//"Private" methods

	//internal method for deactivating all top navigation elements
	MainNavigationBar.prototype._DeactivateTrees = function() {
		
		if (this.nodeActive != null) {
		    if (this.nodeActive.className.match(/Double/)) this.nodeActive.className = "Double";
            else this.nodeActive.className = "";
		}
	};
	
	//internal method for reading cookie 
	MainNavigationBar.prototype._GetCookie = function (name){
	   var i=0;  //Suchposition im Cookie
	   var suche = name+"=";
	   var cook = null;
	   while (i<document.cookie.length){
	      if (document.cookie.substring(i, i+suche.length)==suche){
	         var ende = document.cookie.indexOf(";", i+suche.length);
	         ende = (ende>-1) ? ende : document.cookie.length;
	         cook = unescape(document.cookie.substring(i+suche.length, ende));
	      }
	      i++;
	   }
	  
    return cook;
	};
	
	
	MainNavigationBar.prototype._OpenTree = function(LIActive, thisNavigationBar) {
	    if (LIActive == thisNavigationBar.nodeHover) {
	    
	        //set all other elements passive
		    thisNavigationBar._DeactivateTrees();
		
		    LIActive.className += " Active";
		    thisNavigationBar.nodeActive  = LIActive;
	    }
	}
	
	
	//internal method: mouseoverevent for the list elements
	MainNavigationBar.prototype._Hover = function(LIActive) {
	    var thisNavigationBar   = this;
	    
	    window.clearTimeout(thisNavigationBar.Switch);
		thisNavigationBar.nodeHover = LIActive;
		thisNavigationBar.Switch = window.setTimeout(function () {MainNavigationBar.prototype._OpenTree(LIActive, thisNavigationBar); }, 250);
	};
	
	//internal method: mouseoutevent for the list elements
	MainNavigationBar.prototype._HoverOut = function() {
	    var thisNavigationBar   = this;
	    window.clearTimeout(thisNavigationBar.Switch);
	};
	
	//internal method: find active list nodes for a given navigation level
	MainNavigationBar.prototype._FindActiveListNode = function (nodeParent, iLevel, strActiveNodeID, boolStandard) {
		var thisNavigationBar = this;
		var LI = nodeParent.firstChild;
		var nodeFound = null;
		var iNum = 0;
		
		do {
			if (LI && LI.nodeName == "LI") {
				//things todo on first level nav...
				if (iLevel == 0) {
					LI.onmouseover = function () { thisNavigationBar._Hover(this); };
					LI.onmouseout = function () { thisNavigationBar._HoverOut(); };
					//set this treenode active (if set)
					if (boolStandard) {
						if (iNum == 0) {
							this._Hover(LI);
							nodeFound = LI;	
						}				
					}
					else {
						if (LI.id == strActiveNodeID) {
							this._Hover(LI);
							nodeFound = LI;
						}
					}
				}
				//things todo on second level nav...
				else {
					if (boolStandard) {
						if (iNum == 0) {
							if (LI.className.match(/Last/)) LI.className = "Last Active";
							else LI.className = "Active";
							nodeFound = LI;
						}
						else {
							if (LI.className.match(/Last/)) LI.className = "Last";
							else LI.className = "";
						}
					}
					else {
						if (LI.id == strActiveNodeID) {
							if (LI.className.match(/Last/)) LI.className = "Last Active";
							else LI.className = "Active";
							nodeFound = LI;
						}
						else {
							if (LI.className.match(/Last/)) LI.className = "Last";
							else LI.className = "";
						}
					}				
				}
				iNum++;
			}
			LI = LI.nextSibling;
		}
		while (LI);
		return nodeFound;
	}
	
	//opens the login form overlay
	MainNavigationBar.prototype._OpenLoginForm = function () {
		//clean up a bit...
		var nodeSSOMessages 	=	document.getElementById("SSOMessages");
		while (nodeSSOMessages.firstChild)
			nodeSSOMessages.removeChild(nodeSSOMessages.firstChild);	
		var formLogin		= document.forms["SSOLoginForm"];
		var inputUserName	= formLogin["SSOUser"];
		var inputPassword	= formLogin["SSOPassword"];
		inputUserName.value = MainNavigationCommon.strUNameValue;	
		inputPassword.value = MainNavigationCommon.strPWValue;	
			
		var nodeLoginForm = document.getElementById("SSOLogin");
		nodeLoginForm.style.visibility = "visible";
	};
	
	//closes the login form overlay
	MainNavigationBar.prototype._CloseLoginForm = function () {
		var nodeLoginForm = document.getElementById("SSOLogin");
		nodeLoginForm.style.visibility = "hidden";
	};
	
	
	//reads user info from cookie and returns a PortalUser object
	MainNavigationBar.prototype._ReadUserCookie = function () {
		var NavBar = this;
		var strUserName;
		var strPasswordHash;
		var strActive;
		var User = null;
	    var SSOCookie = null;
		
		//get the cookie
		try 
		{
		    SSOCookie = NavBar._GetCookie("SsoSessionCookie");
		    
		}
		catch(e) {
		    alert (e.description);
		}
		//if (!SSOCookie) alert("No Cookie...");
		
		if (SSOCookie == null) return null;
		
		
				
		var CookieVals = SSOCookie.split(/\&/);
		
		
				
		for (var i = 0; i < CookieVals.length; i++) {
			var Val = CookieVals[i].split(/\=/);
			//alert("cookie: " + CookieVals[i]);
			
			if (Val[0] == 'username') 			strUserName 	= (""+Val[1]).replace(/ /, "\\20");
			if (strUserName != "guest") {
				if (Val[0] == 'passwordhash') 	strPasswordHash = (""+Val[1]).replace(/\+/, "%2B") + "==";
				if (Val[0] == 'active') 		strActive 		= ""+Val[1];
			}
		}
		
		
		
		//alert("Active: " + strActive);
		if (strActive == "True") {
			User = new PortalUser(strUserName, strPasswordHash);
		}
		return User;
	}
	
		
	//"Public" methods
	
	//method for setting the active navigation node(s)
	MainNavigationBar.prototype.SetActiveNodes = function(strActiveNodeID1, strActiveNodeID2) {
		this.strActiveNodeID1 = strActiveNodeID1;
		this.strActiveNodeID2 = strActiveNodeID2;
	};
	
	
	//method to authenticate user
	MainNavigationBar.prototype.SSOAuthenticateUser = function(strUserName, strPassword, boolKeepLoggedIn) {
		var UseSoap = false;
		var NavBar = this;
		var Params = new SOAPClientParameters();
				
		//alert(strUserName + " " + strPassword + " " + boolKeepLoggedIn);
		
		Params.add("user", strUserName);
		Params.add("pass", strPassword);
		Params.add("bKeepLoggedIn", boolKeepLoggedIn);
		SOAPClient.invoke (UseSoap, MainNavigationCommon.strSSOWebServiceUrl, MainNavigationCommon.strSSOWebServiceAuthMethod, Params, false, NavBar._SSOAuthenticateUserCallback );
	}
	
	//method to authenticate user
	MainNavigationBar.prototype.SSOAuthenticateUser = function(strUserName, strPassword, boolKeepLoggedIn, errorMessageContainer) {
		var UseSoap = false;
		var NavBar = this;
		var Params = new SOAPClientParameters();
		MainNavigationCommon.errorMsgContainer = errorMessageContainer;
				
		//alert(strUserName + " " + strPassword + " " + boolKeepLoggedIn);
		
		Params.add("user", strUserName);
		Params.add("pass", strPassword);
		Params.add("bKeepLoggedIn", boolKeepLoggedIn);
		SOAPClient.invoke (UseSoap, MainNavigationCommon.strSSOWebServiceUrl, MainNavigationCommon.strSSOWebServiceAuthMethod, Params, false, NavBar._SSOAuthenticateUserCallback );
	}
	
	//callback method for authentication webservice (called when the service gave a response)
	MainNavigationBar.prototype._SSOAuthenticateUserCallback = function (xml) {
		var nodeSSOMessages 	=	document.getElementById("SSOMessages");
		while (nodeSSOMessages.firstChild)
			nodeSSOMessages.removeChild(nodeSSOMessages.firstChild);

		if (xml.getElementsByTagName("user")[0]) {
			//login successfull
			//alert (xml.getElementsByTagName("user-name")[0].firstChild.data);
			//refresh the page
			location.reload();
		}
		else {
			//login failed
			if (typeof MainNavigationCommon.errorMsgContainer == "undefined")
			{
			    nodeSSOMessages.className = "error";
			    nodeSSOMessages.appendChild(document.createTextNode(MainNavigationCommon.strSSOErrorMessage));
			    nodeSSOMessages.style.display = "block";
			}
			else
			{
			    var nodeSSOMessages 	=	document.getElementById(MainNavigationCommon.errorMsgContainer);
		        while (nodeSSOMessages.firstChild)
			        nodeSSOMessages.removeChild(nodeSSOMessages.firstChild);
			
			    nodeSSOMessages.className = "error";
			    nodeSSOMessages.appendChild(document.createTextNode(MainNavigationCommon.strSSOErrorMessage));
			    nodeSSOMessages.style.display = "block";
			    MainNavigationCommon.errorMsgContainer = "";
			}
		}
	}
	
	MainNavigationBar.prototype.SSOLogoutUser = function() {
	    var UseSoap = false;
		var NavBar = this;
		var Params = new SOAPClientParameters();
		SOAPClient.invoke (UseSoap, MainNavigationCommon.strSSOWebServiceUrl, MainNavigationCommon.strSSOWebServiceLogoutMethod, Params, false, NavBar._SSOLogoutUserCallback );
	}
	
	MainNavigationBar.prototype._SSOLogoutUserCallback = function (xml) {
	    
		if (xml.getElementsByTagName("*")[0].tagName.toLowerCase() == "snpewebservicemessage") {
			//logout successfull
			//alert ("logout!");
			//refresh the page
			//location.reload();
			
			window.location.href = window.location.href + " ";
			location.reload();
			
		}
		
		else {
			//logout failed (and now??? )
		}
	}
	
	
	//method to set the SSO state display (user logged-in or not etc..)
	MainNavigationBar.prototype.SetSSOFragment = function () {
		var NavBar				= this;
		var nodeSSOFragment 	= document.getElementById("SSOFragment");
		var	spanUserName		= document.createElement("span");
		var	aUserName			= document.createElement("a");
		var spanFade			= document.createElement("span");
		var	spanLoginRegister	= document.createElement("span");
		var	spanEmptyPane	    = document.createElement("span");
		var	aLogin				= document.createElement("a");
		var	aLogout				= document.createElement("a");
		var	aRegister			= document.createElement("a");
		var	aSetAsHomepage		= document.createElement("a");
		
		spanUserName.className		= "UserName";
		spanEmptyPane.className		= "EmptyPane";
		spanFade.className			= "Fade";
		spanLoginRegister.className	= "LoginRegister";
		aSetAsHomepage.className	= "SetAsHomepage";
				
		//clear the Fragment first...
		while (nodeSSOFragment.firstChild)
			nodeSSOFragment.removeChild(nodeSSOFragment.firstChild);
		
		aSetAsHomepage.appendChild(document.createTextNode(MainNavigationCommon.strAsHomepage1));
		aSetAsHomepage.appendChild(document.createElement("br"));
		aSetAsHomepage.appendChild(document.createTextNode(MainNavigationCommon.strAsHomepage2));
		aSetAsHomepage.href = "http://www.vol.at/features/vol-als-homepage";
		
		//do only if login-stuff should be visible
		if (this.boolShowLogin) {
							
		    //check if user is logged in...
		    if (this.User) {
			    //do something...
			    aUserName.appendChild(document.createTextNode(this.User.strUserName));
			    //link to user profile
			    aUserName.href= this.strProfileUrl.replace(/###username###/, encodeURI(this.User.strUserName));
			    spanUserName.appendChild(aUserName);
			    spanUserName.appendChild(spanFade);
			    spanUserName.appendChild(document.createElement("br"));
			    aLogout.appendChild(document.createTextNode(MainNavigationCommon.strLogout));
			    aLogout.title = MainNavigationCommon.strLogout;
			    if (this.strLogoutUrl) {
				    aLogout.href = this.strLogoutUrl;
			    }
			    else {
				    aLogout.href = "#";
				    aLogout.onclick = function () {NavBar.SSOLogoutUser(); return false; }
			    }	
    				
    			
			    spanUserName.appendChild(aLogout);
    			
			    nodeSSOFragment.appendChild(spanUserName);
		    }
    		
		    else {
			    //do something else :) ...
			    aLogin.appendChild(document.createTextNode(MainNavigationCommon.strLogin));
			    aLogin.href = this.strLoginUrl;	
			    //only append the onclick event if there is no override for the loginurl		
			    if (!this.strOverrideLoginUrl) {
				    aLogin.onclick = function () { NavBar._OpenLoginForm(); return false };
				    aLogin.href = this.strLoginUrl;
			    }
			    else {
				    aLogin.href = this.strOverrideLoginUrl;
				    aLogin.onclick = function (){};
			    }	
			    aRegister.appendChild(document.createTextNode(MainNavigationCommon.strRegister));
    			
			    aRegister.href = this.strRegisterUrl;
    						
			    spanLoginRegister.appendChild(aLogin);
			    spanLoginRegister.appendChild(document.createTextNode(" " + MainNavigationCommon.strOr + " "));
			    spanLoginRegister.appendChild(document.createElement("br"));
			    spanLoginRegister.appendChild(aRegister);
    			
			    nodeSSOFragment.appendChild(spanLoginRegister);
    			
			    //set stuff in login pane
			    var aRegisterLP 	= document.getElementById("SSOLinkRegister");
			    var formLogin		= document.forms["SSOLoginForm"];
			    var inputUserName	= formLogin["SSOUser"];
			    var inputPassword	= formLogin["SSOPassword"];
			    var aSubmitButton	= document.getElementById("SSOLinkSubmit");
    			
			    aRegisterLP.href 	= aRegister.href;
    			
			    //only use the formaction if there is one defined via the override method
			    // - otherwise we use a onclickevent which tries to login the user via a call
			    //	 to the SNPEWebservice.
			    if (this.strFormAction) {
				    formLogin.action 		= this.strFormAction; 
				    aSubmitButton.onclick	= function () { document.forms['SSOLoginForm'].submit(); return false; };
				    formLogin.onsubmit      = function () {};
			    }
			    else {
				    formLogin.onsubmit		= function () { NavBar.SSOAuthenticateUser(document.forms['SSOLoginForm']["SSOUser"].value, document.forms['SSOLoginForm']["SSOPassword"].value, document.forms['SSOLoginForm']["SSOKeepLoggedIn"].checked); return false; }; 
				    aSubmitButton.onclick 	= function () { NavBar.SSOAuthenticateUser(document.forms['SSOLoginForm']["SSOUser"].value, document.forms['SSOLoginForm']["SSOPassword"].value, document.forms['SSOLoginForm']["SSOKeepLoggedIn"].checked); return false; };
			    }
    			
			    inputUserName.name	= this.strUNameFieldName;
			    inputPassword.name	= this.strPWFieldName;
    						
		    }
		}
		//do only if login-stuff should not be visible
		else {
		    nodeSSOFragment.appendChild(spanEmptyPane);
		}
		nodeSSOFragment.appendChild(aSetAsHomepage);
		
	};
	
	//method: override settings of the navigation bar
	MainNavigationBar.prototype.OverrideSettings = function(strLoginUrl, strLogoutUrl, strRegisterUrl, strFormAction, strUNameFieldName, strPWFieldName, strProfileUrl, boolShowLogin) {
		if (strLoginUrl) 		    this.strOverrideLoginUrl 		= strLoginUrl;
		if (strLogoutUrl) 		    this.strLogoutUrl 				= strLogoutUrl;
		if (strRegisterUrl) 	    this.strRegisterUrl 			= strRegisterUrl;
		if (strFormAction) 		    this.strFormAction				= strFormAction;
		if (strUNameFieldName) 	    this.strUNameFieldName			= strUNameFieldName;
		if (strPWFieldName) 	    this.strPWFieldName				= strPWFieldName;
		if (strProfileUrl) 		    this.strProfileUrl				= strProfileUrl;
		if (boolShowLogin != null)  this.boolShowLogin				= boolShowLogin;
	}
	
	//method: override the user data
	MainNavigationBar.prototype.OverrideUser = function(strUsername, strPasswordHash) {
		if (strUsername) this.User = new PortalUser (strUsername, strPasswordHash);
		else this.User = null;
	}
		
		
	//initialize the navigation
	MainNavigationBar.prototype.Init = function() {
		this.ULNavigation = document.getElementById("MainNavigationBar");
		
		var boolFoundFirst 	= false;
		var boolFoundSecond	= false;
		
		//walk through tree
		var thisNavigationBar = this;
		var ActiveNode1 = this._FindActiveListNode(this.ULNavigation, 0, this.strActiveNodeID1, false);
		
		//if active first level node was found, try to get active second level node
		if (ActiveNode1) {
			var UL = ActiveNode1.firstChild;
			do {
				if (UL && UL.nodeName == "UL") this._FindActiveListNode(UL, 1, this.strActiveNodeID2, false);
				UL = UL.nextSibling;
			}
			while (UL);
		}
		
		//use standard tab(s) if first level node not found
		else {
			var ActiveNode1 = this._FindActiveListNode(this.ULNavigation, 0, "", true);
			if (ActiveNode1) {
				var UL = ActiveNode1.firstChild;
				do {
					if (UL && UL.nodeName == "UL") this._FindActiveListNode(UL, 1, "", true);
					UL = UL.nextSibling;
				}
				while (UL);
			}
		}
		this.SetSSOFragment();
	}
	
// javascripts.js
// Author: Alexander Aberer
// Date: 27.7.2000
// Last modified: 8.6.2001 (Andreas Ritter)
// Last modified: 2.7.2003 (Alexander Aberer)
// Last modified: 19.2.2004 (Stephan Schw&auml;rzler) - Opera
// Last modified: 10.12.2004 (Norbert Kujbus) - Google callback function
// Last modified: 15.01.2005 (Norbert Kujbus) - Remove Google callback function
// Last modified: 14.04.2005 (Csaba Mezo) - Introduce CountIt function
// Last modified: 11.10.2007 (Roland Fischl) - Added getOptimalTabBoxSize function

// !!!Wichtig!!! Die folgende Variable muß gesetzt werden wenn über open_window()
// Seiten auf externen/fremden Webservern geöffnet werden sollen.
if (document.domain.indexOf("vol.at") > -1) document.domain = "vol.at";
var blank_page = "about:blank"; 

function SwitchWebservice(switchform,formelement) {
	var fe, dummy;
	if(typeof formelement != "undefined") {
		fe = formelement;
	} else {
		fe = switchform.elements[0];
	}
	if (fe.selectedIndex != 0) {
		var pulldownindex = fe.selectedIndex;
		var url = fe.options[pulldownindex].value;
		locarray = url.split("|");
		if ( locarray.length > 1 ) {
			windata = locarray[0].split(",");
			dummy = open_window(locarray[1],windata[0],windata[1],windata[2],0,0,"scrollbars=" + windata[3] + ",location=no,toolbar=no,status=no,menubar=no,resizable=yes,dependent=yes");
		} else {
			dummy = open_window(url,"",700,480,10,10,"location=yes,toolbar=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes,dependent=no");
		}
	}
}

function realmedia(path,name,content) {
	var datestr = new Date();
	url = 'http://apps.vol.at/tools/realaudio/embed.asp?cont=' + content + '&title=' + escape(name) + '&file=' + escape(path) + "&" + escape(datestr.toLocaleString());
	if (content=='video') {
		var rc_video=window.open(url,'rc_video','width=230,height=310,resizable=yes');
		rc_video.focus();
	} else {
		var rc_audio=window.open(url,'rc_audio','width=400,height=40');
		rc_audio.focus();
	}
}

function open_window(targetX,name,width,height,posx,posy,windowoptions,init_target) {
	var it, wo, px, py, host,target;
 
	it = targetX;
	wo = "location=no,toolbar=no,status=no,statusbar=no,scrollbars=no,resizable=no,dependent=yes";
	px = py = 0;
	target = targetX;
	
	if(typeof new_window != "undefined") {
		if(new_window.closed != true) {
			new_window.close();
		}
	}

	if (typeof posx != "undefined") px = posx;
	if (typeof posy != "undefined") py = posy;
	if ((typeof windowoptions != "undefined") && (windowoptions != "")) wo = windowoptions;
	
	
	if (typeof init_target != "undefined") {
		it = init_target;
	} else {
		if (targetX.indexOf("http://") != -1) {
			host = "http://" + window.location.hostname;
			if (navigator.appName != "Opera") {
				if (targetX.indexOf(host) == -1) it = blank_page;
			}
		}
	}
	new_window = window.open(it,name,"width=" + width + ",height=" + height + "," + wo);
	//new_window.moveTo(px,py);
	new_window.location.replace(targetX);
	new_window.focus();
	return false;
}

function setUrlForPrint() {
	sUrl = document.location.href;
	if ((document.all) || (document.layers)){
		sUrl = sUrl.replace(/\?/, "\\/");
		sUrl = sUrl.replace(/\&/, "//");
	}
	document.printform.url.value = sUrl;
}

//Script to invoke OEWA measurement on page events (click)
function CountIt(what)
{
	var OEWA1="http://austria.oewabox.at/cgi-bin/ivw/CP/"+what;
	var OEWA2="http://a-vol.oewabox.at/cgi-bin/ivw/CP/"+what;
	var counter1 = new Image;
	var counter2 = new Image;
	counter1.src = OEWA1+"?r="+escape(document.referrer);
	counter2.src = OEWA2+"?r="+escape(document.referrer);
}

// Function for URL (GET) Parameter
function getURLParam(name) {
	var q = document.location.search;
	var i = q.indexOf(name + '=');
	if (i == -1) {
		return false;
	}
	var r = q.substr(i + name.length + 1, q.length - i - name.length - 1);
	i = r.indexOf('&');
	if (i != -1) {
		r = r.substr(0, i);
	}
	return r.replace(/\+/g, ' ');
}

// resizes a window depending on its content and a given width to the optimal size
function resizeWindowToOptimalSize(oW,divId) {
    if( !document.getElementById ) return false;
    var oH = document.getElementById(divId); if( !oH ) { return false; }
    var oH = oH.clip ? oH.clip.height : oH.offsetHeight; if( !oH ) { return false; }
    window.resizeTo( oW, oH );
    var myW = 0, myH = 0, d = document.documentElement, b = document.body;
    if( window.innerWidth ) { myW = window.innerWidth; myH = window.innerHeight; }
    else if( d && d.clientWidth ) { myW = d.clientWidth; myH = d.clientHeight; }
    else if( b && b.clientWidth ) { myW = b.clientWidth; myH = b.clientHeight; }
    if( window.opera && !document.childNodes ) { myW += 16; }
    window.resizeTo( oW + ( oW - myW ), oH + ( oH - myH ) );
}

function open_window_astitle(target,name,width,height) { 
	void(open_window(target,name,width,height));
}

//get height of given divId
function getOptimalTabBoxSize(divId) {
    if( !document.getElementById ) return false;
    var oH = document.getElementById(divId); if( !oH ) { return false; }
    var oH = oH.clip ? oH.clip.height : oH.offsetHeight; if( !oH ) { return false; }
    return oH;
}

var bDebug = true;
function getBanmanSequence(zoneid,count) {
	if (typeof count == "undefined") count = 0;
	var rns = (new String (Math.random())).substring (2, 11);
	var aId = "sequence-" + zoneid + "-" + rns;
	var sURL = "/lassdichueberraschen/sequence2.aspx" + "?ZoneID=" + zoneid + "&CountImpressions=True&Total=" + count + "&SiteID=1" + "&Random=" + rns;
	document.write("<div id=\"" + aId + "\" style=\"margin:0;padding:0;\"></div>");
	ajaxAdvert(sURL, aId, true);
}
function getBanmanAd(zoneid) {
	var rns = (new String (Math.random())).substring (2, 11);
	var aId = "ad-" + zoneid + "-" + rns;
	var sURL = "/mehrueberraschungen/ad.aspx" + "?ZoneID=" + zoneid + "&Task=Get&Browser=NETSCAPE4&PageID=1205&Random="+rns;
	document.write("<div id=\"" + aId + "\" style=\"margin:0;padding:0;\"></div>");
	ajaxAdvert(sURL, aId, false);
}

function ajaxAdvert(url, containerid, isSequence) {
	var page_request = false;
	if (window.XMLHttpRequest) // if Mozilla, Safari etc
		page_request = new XMLHttpRequest()
	else if (window.ActiveXObject){ // if IE
		try {
			page_request = new ActiveXObject("Msxml2.XMLHTTP")
		} catch (e){
			try{
				page_request = new ActiveXObject("Microsoft.XMLHTTP")
			} catch (e){}
		}
	}
	else
		return false
	page_request.onreadystatechange=function(){
		loadAdvert(page_request, containerid, isSequence)
	}
	page_request.open("GET", url, true)
	page_request.send(null)
	return true
}

function loadAdvert(page_request, containerid, isSequence) {
	if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)) {
		var ajaxcontent = page_request.responseText;
		if(!ajaxcontent.match(/ISAPI/)) {
			if (isSequence) {
				ajaxcontent = ajaxcontent.replace(/document\.write\(\'/gi, "").replace(/([^\\])\'\);\s*/gi, "$1").replace(/\\\"/gi, "\"").replace(/\\\'/gi, "\'").replace(/\\r/g, "\r");
				var adCells = ajaxcontent.match(/<td>/gi);
				if (adCells) {
					for (var i = 0; i < adCells.length; ++i) {
						if ((i % 2) != 0)
							ajaxcontent = ajaxcontent.replace(/<td>/i, "<td class='even'>");
						else
							ajaxcontent = ajaxcontent.replace(/<td>/i, "<td class='odd'>");
					}
				}
			} else {
				ajaxcontent = ajaxcontent.replace(/document\.write\(\'/gi, "").replace(/([^\\])\'\);.*/gi, "$1").replace(/\\\"/gi, "\"").replace(/\\r/g, "\r");
			}
			document.getElementById(containerid).innerHTML = ajaxcontent;
		}
	}
}

//***SearchBox***
//prototype object: SearchBox
function SearchBox(sContainerNodeID) {
	this.ContainerNodeID = sContainerNodeID;
	this.nodeContainer = null;
	this.horTabs = null;
	this.verTabs = null;
	this.arrTabs = new Array();
	this.searchWord = ""; //use this if you want to fill the searchbox with any search word on startup
	this.lastActiveTab = 1;
	var SearchBox = this;
	
	//CSS definitions
	this.ActiveClass = "Active";
	this.LastClass = "Last";
	this.HorTabsID = "horTabs";
	this.VerTabsID = "morelist";
	this.NoSearchTabID = "NoSearchTab";
	this.HiddenDivID = "shadow_gray";
	this.ArrowName = "arrow";
	this.ArrowUp = "/SysRes/DotcomSkin/Img/SearchBox/Buttons/arrowUp.png";
	this.ArrowDown = "/SysRes/DotcomSkin/Img/SearchBox/Buttons/arrowDown.png";
	this.VerTabsItemID = "listitem";
	this.VerTabsSpaceholderItemID = "spaceholder";
	this.SearchFormID = "searchbox";
	this.PageBodyID = "Dotcom_Body";
	
	if (document.getElementById(sContainerNodeID))
		this.nodeContainer = document.getElementById(sContainerNodeID);
	
	if (this.nodeContainer != null)	
    {
        this.horTabs = document.getElementById(this.HorTabsID);
        this.verTabs = document.getElementById(this.VerTabsID);
        
        
        this.horLIs = this.horTabs.getElementsByTagName("li");
        this.verLIs = this.verTabs.getElementsByTagName("li");
        


        // Traverse through horizontal li elements
        for (var i = 0; i < this.horLIs.length; ++i) {
            this.horLIs[i].className = '';
            
            var TabTitle = this.FindFirstChild(this.horLIs[i], "H3");
            var Content = this.FindFirstChild(this.horLIs[i], "FORM");
            
            this.CleanUp(this.horLIs[i]);
             
            if (TabTitle != null && Content != null)
            {
                this.AddTab("HorTab" + i, TabTitle.innerHTML, TabTitle.className, Content);
                
                var a = document.createElement("a");
                
                if (this.horLIs[i].id != this.NoSearchTabID)
                {
                    var OnClickEvent = function () { SearchBox.CopySearchWord(); SearchBox.Activate(this.id, true); SearchBox.Visibility("off"); }; 
                }
                else
                {
                    var OnClickEvent = function () { 
                        SearchBox.Activate(this.id, false);
                        
                        if ("none" == document.getElementById(SearchBox.HiddenDivID).style.display || document.getElementById(SearchBox.HiddenDivID).style.display == "")
                        {
                            SearchBox.Visibility("on"); 
                        }
                        else
                        {
                            SearchBox.Visibility("off"); 
                        }
                    }; 
                }
                a.href = "javascript:void(0);";
                a.onclick = OnClickEvent;
                a.id = "HorTab" + i;
                a.style.cursor = "pointer";
                
                a.innerHTML = TabTitle.innerHTML;
                this.horLIs[i].appendChild(a);
            }
        }
        
        
        // Traverse through vertical li elements
        for (var i = 0; i < this.verLIs.length; ++i) {
            this.verLIs[i].className = '';
            
            var Tab = this.FindFirstChild(this.verLIs[i], "A");
            
            this.CleanUp(this.verLIs[i]);
            
            if (Tab != null)
            {
                this.verLIs[i].appendChild(Tab);
                
                if (this.verLIs[i].innerHTML != "")
                {
                    this.verLIs[i].className = this.VerTabsItemID;
                }
                else
                {
                    //blank LI is used as spaceholder for seperating list
                    this.verLIs[i].className = this.VerTabsSpaceholderItemID;
                }
            }
        }
        
    
        //define MouseEvents for Morelist
        var MoreListON = function () { 
            if (typeof moreListTimeout != "undefined")
                clearTimeout(moreListTimeout); 
            
            SearchBox.Visibility("on"); 
        };
        
        var MoreListOFF = function () { 
            if (typeof moreListTimeout != "undefined")
                clearTimeout(moreListTimeout);
                
            SearchBox.reactivateLastActiveTab();
            SearchBox.Visibility("off");
        };
        
        var delayedMoreListOFF = function () { 
            if (typeof moreListTimeout != "undefined")
                clearTimeout(moreListTimeout);
            
            moreListTimeout = setTimeout(function(){SearchBox.Visibility("off");SearchBox.reactivateLastActiveTab();},1500);     
        };
          
              
	    //event for click on SearchBox (either textBox or button)
        var searchFormular = document.getElementById(this.SearchFormID);
        searchFormular.onmouseup = MoreListOFF;  //close list immediately if there was a click on the searchbox
            
        //events for LIs in morelist
        var ULMorelist = document.getElementById(this.VerTabsID);
        ULMorelist.onmouseover = MoreListON; //if mouse is over Morelist, fire this event to prevent closing the list
        ULMorelist.onmouseout = delayedMoreListOFF; //do not close list immediately, give the user a second, perhaps he slipped out
        ULMorelist.onclick = MoreListOFF; //close list, although the page will be left...


        //events for the whole page
        var pageBody = document.getElementById(this.PageBodyID);
        pageBody.onmouseup = delayedMoreListOFF;
        
        //prevent, that the H3s and FORMs on load of page are visible -> set visibility to visible in order to make the A elements visible
        this.horTabs.style.visibility = 'visible';
    }
}



			//activate this tab including form an background onload
			SearchBox.prototype.ActivateOnLoad = function (iNumber)
			{
				if (this.nodeContainer != null)	
                {
				    TabIdByNumber = this.arrTabs[iNumber-1].sTabID;
    				
				    this.Activate(TabIdByNumber,true);				
				}
			}
			
			
			//method for finding the first child node with a certain node name
			SearchBox.prototype.FindFirstChild = function (nodeParent, sNodeName) {
				var nodeChild = nodeParent.firstChild;
				do {
					if (nodeChild && nodeChild.nodeName == sNodeName)
						return nodeChild;
					
					nodeChild = nodeChild.nextSibling;
				}
				while (nodeChild);
				return null;
			}
			
			
			//method for adding a Tab to Array
			SearchBox.prototype.AddTab = function(sTabID, sTabName, sBackgroundClass, ContentNode) {
					var newtab = new SearchBoxTab (sTabID, sTabName, sBackgroundClass, ContentNode);
					this.arrTabs.push(newtab);
			}
			
				
			//method for assigning a tab to class "Active"
			SearchBox.prototype.SetActiveTab = function(iNumber) {
			    //active tab is in class "Active"
			    for (var i = 0; i <= this.horLIs.length-1; i++)
			    {
			        this.horLIs[i].className = "";
			        
			        if (i == iNumber-1)
			        {
			            this.horLIs[iNumber-1].className = this.ActiveClass;
			        }
			    }
			    
			    //last tab is in class "Last"
			    this.horLIs[this.horLIs.length-1].className += " " + this.LastClass;
			}
			
			
			//method for reactivating the last active tab
			SearchBox.prototype.reactivateLastActiveTab = function() {
					TabIdByNumber = this.arrTabs[this.lastActiveTab-1].sTabID;
				    this.Activate(TabIdByNumber,false);	
			}
			
			
			//method for activating or deactivating the morelist
			SearchBox.prototype.Visibility = function(sOption) {
					var SearchBox = this;
	
					divChanger = document.getElementById(this.HiddenDivID); 
					arrowPicture = document.getElementsByName(this.ArrowName);
								
					if (sOption == "on")
					{
						divChanger.style.display = 'block';
						arrowPicture[0].src = this.ArrowUp;
					}
								 
					if (sOption == "off")
					{
						divChanger.style.display = 'none';
						arrowPicture[0].src = this.ArrowDown;
					}
			}
							
			
			//method for cleaning up the H3 and FORM elements which are replaced by an A element
			SearchBox.prototype.CleanUp = function(nodeContainer) {
			    //clean up and remove all childs in container
			    while (nodeContainer.firstChild)
			        nodeContainer.removeChild(nodeContainer.firstChild)
			}
			
			
			//if user clicks on a Tab, this method looks in array which tab has been clicked and sets the active tab and changes the background
			SearchBox.prototype.Activate = function(id, bDrawContent) {
			    this.id = id;
			    this.bDrawContent = bDrawContent;
			    
			    var iIndex = this.GetIndexOfTabID(this.id);
			    this.SetActiveTab(iIndex+1);
			    
			    //change background image
		        var searchBackground = document.getElementById(this.ContainerNodeID);
		        
		        bgClass = this.arrTabs[iIndex].sBackgroundClass;
		        searchBackground.className = bgClass;
			        
			    if (this.bDrawContent)
			    {
			        this.lastActiveTab = iIndex+1;
			        this.DrawContent(iIndex);
			    }
			}
			
			
			//this method puts the content of the FORM in an DIV (searchbox)
			SearchBox.prototype.DrawContent = function(iIndex) {
			    if (iIndex != null)
			    {
			        //includes the html elements for the new search 
			        newSearch = this.arrTabs[iIndex].nodeContent;
			            
			        var eSearchForm = document.getElementById(this.SearchFormID);
			        this.CleanUp(eSearchForm);
			        
			        //repleace the current search form
			        eSearchForm.appendChild(newSearch);
			        
			        //pastes the copy of the last active search to the new search
			        this.PasteSearchWord();
			    }
			}
			
			
			//this method finds the index of a Tab by TabID
			SearchBox.prototype.GetIndexOfTabID = function (sTabID) {
			    for (var i = 0; i <= this.arrTabs.length-1; i++)
			    {
			        var iIndex = this.arrTabs[i].sTabID == sTabID ? i : null;
			        
			        if(iIndex != null)
			            return iIndex;
			    }
			}
			
			
			//this method creates a copy of the last active search
			SearchBox.prototype.CopySearchWord = function () {
			    for (var i = 0; i < document.searchForm.length; ++i) {
                  if (document.searchForm.elements[i].type == "text")
                  {
                    this.searchWord = document.searchForm.elements[i].value;
                  }
                }
			}
			
			
			//this method pastes the copy of the last active search to the new search
			SearchBox.prototype.PasteSearchWord = function () {
			    for (var i = 0; i < document.searchForm.length; ++i) {
                  if (document.searchForm.elements[i].type == "text")
                  {
                    document.searchForm.elements[i].value = this.searchWord;
                  }
                }
			}
			




//object: SearchBoxTab
function SearchBoxTab(sTabID, sTabName, sBackgroundClass, nodeContent) {
    //properties & defaults
    this.sTabName = "New Tab";
    this.nodeContent = null;
    this.sTabID = null;
    this.sBackgroundClass = null;

    //set properties
    if (nodeContent)
	    this.nodeContent = nodeContent;
    if (sTabName)
	    this.sTabName = sTabName;
    if (sTabID)
	    this.sTabID = sTabID;
	if (sBackgroundClass)
	    this.sBackgroundClass = sBackgroundClass;
}




//prototype object: Banner
function Banner(divid) {
    this.DivID = divid;
    this.Height = 45;
    this.i = 0;
}

            //this method calls every 10ms the minimize method
			Banner.prototype.Animate = function() {
			    var Banner = this;
			    
			    //execute function every 10ms
			    setInterval(function() {Banner.Minimize();},10);
			}
			
			
			//this method reduces the height of the DIV and removes it out of DOM
			Banner.prototype.Minimize = function() {
			    this.i = this.i + 1;
			    height = 0 - this.i;
			    bannerdiv = this.DivID;
			
			    bannerNode = document.getElementById(bannerdiv);
			
			    if (bannerNode)
			    {
			        bannerNode.style.backgroundPosition = '0px ' + height + 'px';
			
			        if (height * -1 >= this.Height)
			        {
			            //remove div
			            var parentNode = bannerNode.parentNode;
			            var childNodes = parentNode.childNodes;
			            
			            for (var j = 0; j < childNodes.length; j++) {
			                var a = childNodes[j].id;
			                if (a && a==bannerdiv) {
			                    parentNode.removeChild(childNodes[j]);
			                }
			            }
			            return true;
			        }
			    }
			}
isNS4 = ((document.layers) ? true : false);
isIE4 = ((document.all && !document.getElementById) ? true : false);
isIE5 = ((document.all && document.getElementById) ? true : false);
isNS6 = ((!document.all && document.getElementById) ? true : false);
ie4=document.all&&navigator.userAgent.indexOf("Opera")==-1
dom=document.getElementById&&navigator.userAgent.indexOf("Opera")==-1

function isPPC() {
    if (navigator.appVersion.indexOf("PPC") != -1) return true;
    else return false;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0 && a[i].length>0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_setTextOfTextfield(objName,x,newText) { //v3.0
  var obj = MM_findObj(objName); if (obj) obj.value = newText;
}

function openEventsHeute() {
MM_openBrWindow('events_heute.php3?parent=main','events_heute','scrollbars=yes,resizable=yes,width=250,height=500,top=80,left=760');
	document.cookie="windowopen=1";
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);

function MM_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}
/* Functions that swaps images. */
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function execonload()
{
	if (document.layers) {
		if (document.layers['Nav1']) {
			redrawnav()
		}
	}
	if (document.all) {
		if (document.all['Nav1']) {
			redrawnav()
		}
	} else {
		if (document.getElementById) {
			if (document.getElementById('Nav1')) {
				redrawnav()
			}	
		}
	}
}

function setregtext(txt)
{
	if (isNS4) {
		if (document.layers['regtxt']) {
			var lyr = document.layers['regtxt'].document;
			lyr.open();
			lyr.write(txt);
			lyr.close();
		}
	}
	if (isIE4) {
		if (document.all['regtxt']) {
			document.all['regtxt'].innerHTML = txt;
		}
	}
	if (isNS6 || isIE5) {
		var e
		if (document.getElementById('regtxt')) {
			e=document.getElementById('regtxt')
			e.innerHTML = txt;
		}
	}
}

function clipTo(obj,t,r,b,l) {
	if (document.layers) {
		obj.clip.top = t
		obj.clip.right = r
		obj.clip.bottom = b
		obj.clip.left = l
	}
	else {
		obj.clip = "rect("+t+"px "+r+"px "+b+"px "+l+"px)"
		
	}
}

function clipValues(obj,which) {
	if (document.layers) {
		if (which=="t") return obj.clip.top
		if (which=="r") return obj.clip.right
		if (which=="b") return obj.clip.bottom
		if (which=="l") return obj.clip.left
	}
	else {
		
		var clipv = obj.clip.split("rect(")[1].split(")")[0].split("px")				
		
		
		
		if (which=="t") ix=0
		if (which=="r") ix=1
		if (which=="b") ix=2
		if (which=="l") ix=3
		
		
		
		if ( obj.clip.indexOf(",")>0) { 
			return Number(clipv[ix].substr(2,clipv[ix].length-2))
		} else {
			return Number(clipv[ix])
		}
		
		
		
	}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function replaceChar(string, from, to){
         //replaces from with to in string
         var i = string.indexOf(from);
         
         if(i == -1) return string;  //base case
         else return(string.substring(0,i) + to +
              replaceChar(string.substring(i+1,string.length),from,to));
           

}

/*
function CleanFormField(args) {
	 for (var i=0; i<CleanFormField.arguments.length; i++) {
		var mystr=CleanFormField.arguments[i].value
		mystr=replaceChar(mystr,'Â–', unescape('%2D')) 
		mystr=replaceChar(mystr,'Â’', unescape('%27')) 
		mystr=replaceChar(mystr,'Â„', unescape('%22')) 
		mystr=replaceChar(mystr,'Â“', unescape('%22'))
		mystr=replaceChar(mystr,'Â®', '') 
		CleanFormField.arguments[i].value=mystr
		
	}
}
*/

function getElemPosX(elemname,relto)
{
	myelem=document.images[elemname]?document.images[elemname]:document.getElementById(elemname);
	
	if (!myelem)
	{
		return 0;	
	} else
	{
		if (1)
		{
			el=myelem;
			var pos = 0;
		     do  {
		         pos += el.offsetLeft;
		      	 el = el.offsetParent;
		      	 
		     }
		     while (el);
		}	
		
		if (relto)
		{
			x=getElemPosX(relto)
			pos=pos-x
		}
		
		return pos
	}
}

function getElemPosY(elemname,relto)
{
	myelem=document.images[elemname]?document.images[elemname]:document.getElementById(elemname);
	
	if (!myelem)
	{
		return 0;	
	} else
	{
		if (1)
		{
			el=myelem;
			var pos = 0;
		     do  {
		         pos += el.offsetTop;
		      	 el = el.offsetParent;
		      	 
		     }
		     while (el);
		}	
		
		if (relto)
		{
			y=getElemPosY(relto)
			pos=pos-y
		}
		
		return pos
	}
}

function printfire()
{
    if (document.createEvent)
    {
        printfire.args = arguments;
        var ev = document.createEvent("Events");
        ev.initEvent("printfire", false, true);
        dispatchEvent(ev);
    }
}

 var timerActive = false;
 var timerVal = '5';
 //var testex = /\?timer\=(\d+)/;
 var pagetimer;

 // preload images

 var imgPlay = new Array();
 imgPlay[0] = new Image(); imgPlay[0].src = "/SysRes/DotcomSkin/Img/ImageDisplayer/button_play01.gif";
 imgPlay[1] = new Image(); imgPlay[1].src = "/SysRes/DotcomSkin/Img/ImageDisplayer/button_play02.gif";
 var imgPause = new Array();
 imgPause[0] = new Image(); imgPause[0].src = "/SysRes/DotcomSkin/Img/ImageDisplayer/button_stop01.gif";
 imgPause[1] = new Image(); imgPause[1].src = "/SysRes/DotcomSkin/Img/ImageDisplayer/button_stop02.gif"; 

 // do not modify this line - !!!new style!!!

/*
 if (testex.test(window.location.search)) {
     testex.exec(window.location.search);
     if (parseInt(RegExp.$1) > 0) {
        timerActive = true;
        timerVal = parseInt(RegExp.$1);
    }
}
*/

//ie bugfix for disappaering pictures
function showImageAgain() {
    try {
        document.getElementById("nextLinkImageContainer").style.display = "none";
        document.getElementById("nextLinkImageContainer").style.display = "block";
       //document.getElementById("ImageLink").style.display = "block";
     }
     catch(e) { }
     return false;
}


function initTimerControl() {
    if(document.getElementById) {
        //alert('timerActive:' + timerActive);        
        if (!timerActive) {
            document.getElementById("timerInfoButton").src = imgPlay[1].src;
            //document.getElementById("timerInfoText").firstChild.nodeValue = "automatisch abspielen";
            } 
        else {
            document.getElementById("timerInfoButton").src = imgPause[1].src;
            //document.getElementById("timerInfoText").firstChild.nodeValue = "diashow stoppen";
         }
    }
}
function toggleControl() {
      if (timerActive) {
          timerActive=false;
          pauseIt();
          document.getElementById("timerInfoButton").src = imgPlay[1].src;
          //document.getElementById("timerInfoText").firstChild.nodeValue = "automatisch abspielen";
      } 
      else {
          timerActive=true;
          startIt();
          document.getElementById("timerInfoButton").src = imgPause[1].src;
          //document.getElementById("timerInfoText").firstChild.nodeValue = "diashow stoppen";
      }
      return false;
 }

 function setTimer(mode) {
    pauseIt();
    if(document.getElementById) {
        switch (mode) {
            case "inc":
                if (timerVal < 99) timerVal += 1;
                break;
            case "dec":
                if (timerVal > 0) timerVal -= 1;
                break;
                default:
                break;
        }
        //document.getElementById("timerValue").firstChild.nodeValue = timerVal + timerPostfix;
    }
    startIt();
 }

 function startIt() {
    clearTimeout(pagetimer);
    pagetimer = setTimeout("pageNav('next', '?timer=' + timerVal)", timerVal * 1000);
    timerActive = true;
 }

 function pauseIt() { 
    clearTimeout(pagetimer);
    timerActive = false;
 }

 function pageNav(dir, qs) {
    var query = (typeof qs != "undefined") ? qs : "";
    switch (dir) {
        case "prev":
            window.location.href = prevPage + query;
            break;
        case "next":
            default:
            var linkelement = document.getElementsByName('nextLinkImage');
            if (typeof linkelement[0] != "undefined")
            {
                var linkstr = linkelement[0].onclick.toString();
                
                //var functionString = linkstr.match(/(AjaxGet\(.+);/);
                var functionString = linkstr.slice(linkstr.indexOf('AjaxGet'),linkstr.lastIndexOf(';')+1);
                //AjaxGet('/engine.aspx?page=image-detail&fotoImageIndex=2&city=bregenz&event=Saturday%20Night%20Fever%20@%20Enjoy&EventID=151207_Satureday_Night_Fever_im_Enjoy','image-detail','image-detail-paging','Dotcom_ImageDisplayer');
                //window.location.href = nextPage + query;
                
                //document.write(functionString); 
                eval(functionString);
            }
            else
            {
                toggleControl();
            }
            
           
            var linkelementDiv = document.getElementById('nextLinkImageDiv');
            if (linkelementDiv != null)
            {
                var linkstrDiv = linkelementDiv.attributes['onclick'].nodeValue;
                var functionStringDiv = linkstrDiv.slice(linkstrDiv.indexOf('AjaxGet'),linkstrDiv.lastIndexOf(';')+1);
                eval(functionStringDiv);
            }
            
            
            startIt();
            break;
    }
 }

 function swapImage(imgid, swapimg) {
    if(document.getElementById) {
        document.getElementById(imgid).src = swapimg.src;
    }
 }

 function swapInfo(eid, evt) {
    if(document.getElementById) {
        if (timerActive) {
            if ((document.getElementById(eid + 'Button').src != imgPause[evt].src) && (imgPause[evt].complete)) {
                document.getElementById(eid + 'Button').src = imgPause[evt].src;
            }
            } else {
                if ((document.getElementById(eid + 'Button').src != imgPlay[evt].src) && (imgPlay[evt].complete)) {
                document.getElementById(eid + 'Button').src = imgPlay[evt].src;
            }
        }
    }
 }
 

 function openLeft() {
    if (window.parent.location==window.location) {
        window.resizeTo(755,650); // stand-alone dia page (no thumbnail navigation)
    } 
    else {
        if (window.location.pathname.indexOf(firstPage) > -1) {
            window.parent.thumbnailFrame.location.replace(thumbPage);
        }
    }
 }

 function openRight() {
    if (window.parent.location==window.location) {
    } 
    else {
        if (window.location.pathname.indexOf(firstPage) > -1) {
            window.parent.rightFrame.location.replace("http://pixcentral.tele.net/dotcom_right.asp?category="+masterId);
        }
    }
 } 
 
 
    
function checkForTagging() {
  ImageLinkVar = document.getElementById('ImageLink');
  
  if (UserIsAuthenticated == true)
  {
    ImageLinkVar.style.cursor = "crosshair";
    ImageLinkVar.onclick = function(event) { return setNameTag(event); }
    ImageLinkVar.attributes.getNamedItem("href").nodeValue = "javascript:;";
    
    //remove paging
    removePaging();
  }
  else
  {
    showDiv('taggingInfo','SSOAdditionalLogin');
  }
}

function removePaging() {
    ImageLinkContainerVar = document.getElementById('nextLinkImageContainer');
    ImageLinkContainerVar.onclick = function() {  }
    
    //prevLinkImageDiv = document.getElementById('prevLinkImageDiv');
    //nextLinkImageDiv = document.getElementById('nextLinkImageDiv');
    
    //prevLinkImageDiv.style.visibility = 'hidden';
    //nextLinkImageDiv.style.visibility = 'hidden';
}


function showDiv(Id, closeId){
  
  if (Id != "" )
  {
    showDivId = document.getElementById(Id);
    
    if (closeId != "")
    {
        closeDivId = document.getElementById(closeId);
        
        if (closeDivId.style.visibility == 'visible')
        {
            closeDivId.style.visibility = 'hidden';
            showDivId.style.visibility = 'visible';
        }
        else
        {
            showDivId.style.visibility = 'visible';
        }
    }
  }
  else
  {
    showDivId.style.visibility = 'visible';
  }
  document.getElementById('pagerPanel').style.zIndex=120;
}

function hideDiv(Id){
  if (Id != "")
  {
    divId = document.getElementById(Id);
    divId.style.visibility = 'hidden';
    document.getElementById('pagerPanel').style.zIndex=100;
  }
}


function showNameTagSub(id) {
    document.getElementById(id).style.display = "block";
}

function hideNameTagSub(id) {
    document.getElementById(id).style.display = "none";
}

function switchNameTags() {
    el = document.getElementById('nametags');
    sw = document.getElementById('nametagswitch');
    if(el.style.visibility == 'visible')
    {
        el.style.visibility = "hidden";
        sw.innerHTML = 'Namensschilder anzeigen';
    }
    else
    {
        el.style.visibility = "visible";
        sw.innerHTML = 'Namensschilder verstecken';
    }
}


// xmlHttpRequest Objektinstanz
var xhttp;
var divContainerId;
      
function getUser(myUserName,friendsUserName,divContainer) {
    //alert(document.getElementById('NameTagFieldSub_174373').childNodes[0]);
    userInformationContainer = document.getElementById(divContainer);
    if (userInformationContainer.getElementsByTagName('table').length == 0)
    {
        if (window.ActiveXObject){
            try{
                //Internet Explorer 6.x
                xhttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch(e){
                //IE 5.x
                try{
                    xhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch(e){
                    xhttp = false;
                }
            }
        } 
        else if(window.XMLHttpRequest){
            // Mozilla, Opera und Safari
            try{
                xhttp = new XMLHttpRequest();
            }
            catch(e){
                xhttp = false;
            }
        }
        
        
        if (xhttp!=null)
        {
            divContainerId = divContainer;
            
            // onReadyStateChange Handler
            xhttp.onreadystatechange=callBack_getUser;
            
            // asynchronen GET Request vorbereiten
            xhttp.open('GET', '/' + myUserName + '/@@immagetagging?requestusr=' + friendsUserName, true);
            
            // leerer Body da kein POST
            xhttp.send(null);
        }
        else
        {
            alert("Your browser does not support XMLHTTP.");
        }
    }
}

function callBack_getUser() {
  //loaded (4) and OK (200)?
  if (xhttp.readyState==4 && xhttp.status==200) {
    var userData;
    try {
      var userData = eval('('+xhttp.responseText+')'); // JSON "parsen"
    } 
    catch(e) {
      //alert('eval: Ungltiges JSON: ' + e);
    }
    
    //create content
    if (typeof userData != 'undefined')
    {
        var content;
                                                     
        content =  '<table border="0" width="100%">';
          content += '<tr>';
            content += '<td align="center" width="20%">';
              content += '<img src="http://apps.vol.at/tools/thumbgen/thumb.ashx?maxw=65&maxh=65&url=' + userData['thumbURL'] + '" alt="Das ist ' + userData['username'] + '!" />';
            content += '</td>';
            content += '<td valign="top" width="70%" align="left">';
              content += '<table width="99%" class="Dotcom_NameTagText">';
                content += '<tr>';
                  content += '<td align="left">';
                    content += userData['username'];
                  content += '</td>';
                  content += '<td align="right">';
                    content += "<a class=\"Dotcom_Close\" href=\"javascript:void(0);\" name=\"close\" onclick=\"javascript:hideNameTagSub('" + divContainerId + "');\"></a>";
                  content += '</td>';
                content += '</tr>';
              content += '</table>';
            
              content += '<table border="0" class="Dotcom_NameTagText" style="font-weight:normal;">';
                if (userData['town'] != null)
                {
                content += '<tr>';
                  content += '<td>';
                      content += 'Ort: ' + userData['town'];
                  content += '</td>';
                content += '</tr>';
                }
                if (userData['favoriteMusic'] != null)
                {
                content += '<tr>';
                  content += '<td>';
                      content += 'Lieblingsmusik: ' + userData['favoriteMusic'];
                  content += '</td>';
                content += '</tr>';
                }
              content += '</table>';
              
            content += '</td>';
          content += '</tr>';
        content += '</table>';
        
       content += '<table >';
          content += '<tr>';
            content += '<td colspan="2">';
              content += '<a class="Dotcom_NameTagLink" target="_blank" href="http://freunde.vol.at/' + userData['username'] + '/@@sendmessage.html">Private Nachricht senden</a>';
              content += '&nbsp;&nbsp;|&nbsp;&nbsp;';
              content += '<a class="Dotcom_NameTagLink" target="_blank" href="http://freunde.vol.at/' + userData['username'] + '">Zur Memberpage</a>';
            content += '</td>';
          content += '</tr>';
        content += '</table>';

          
        insertDiv = document.getElementById(divContainerId);
        insertDiv.innerHTML = "";
        insertDiv.innerHTML = content;
    }
  }
}

//mouseover function for social bookmarks
function toggleBookmark(serviceName,active) {
    var serviceText = document.getElementById("serviceNameField");
    var serviceImg = document.getElementById(serviceName);
              
    if (serviceName != "" && active == true) {
      switch (serviceName) {
        case 'wong':
          serviceNameText = "Mr. Wong";
          serviceImgSrc = "/SysRes/DotcomSkin/Img/SocialBookmarks/wong_b.png";
          break;
        case 'Yigg':
          serviceNameText = "Yigg";
          serviceImgSrc = "/SysRes/DotcomSkin/Img/SocialBookmarks/yigg_b.png";
          break;
        case 'Digg':
          serviceNameText = "Digg";
          serviceImgSrc = "/SysRes/DotcomSkin/Img/SocialBookmarks/digg_b.png";
          break;
        case 'Delicious':
          serviceNameText = "del.icio.us";
          serviceImgSrc = "/SysRes/DotcomSkin/Img/SocialBookmarks/delicious_b.png";
          break;
        case 'StumbleUpon':
          serviceNameText = "Stumble Upon";
          serviceImgSrc = "/SysRes/DotcomSkin/Img/SocialBookmarks/stumbleupon_b.png";
          break;
        case 'Technorati':
          serviceNameText = "Technorati";
          serviceImgSrc = "/SysRes/DotcomSkin/Img/SocialBookmarks/technorati_b.png";
          break;
        default: serviceNameText = ""; break;
      }
      
      lastServiceImgSrc = serviceImg.src;
      serviceText.innerHTML = serviceNameText;
      serviceImg.src = serviceImgSrc;
    }
    else
    {
      serviceText.innerHTML = "";
      serviceImg.src = lastServiceImgSrc;
    }
}