// go to function pageLoaded() when the whole document is loaded
Event.observe(window, 'load', pageLoaded);

function pageLoaded() {
	startlist();
}

// documentation please!
function startlist() {
  if (document.all&&document.getElementById) {
    navRoot = document.getElementById("sl_nav");
    for (i=0; i<navRoot.childNodes.length; i++) {
      node = navRoot.childNodes[i];
      if (node.nodeName=="LI") {
        node.onmouseover=function() {
          this.className+=" over";
        }
        node.onmouseout=function() {
          this.className=this.className.replace
          (" over", "");
        }
      }
    }
  }
}

// if there is no horizontal advertising
// change the postion of div#advertising_horizontal
function setAdvertisingStyle(LeaderBoard) {
	if (LeaderBoard != 1) {
		$('advertising_horizontal').setStyle({position: 'absolute', top: '-5px'});
	}
}

// check if there is a horizontal banner
// if not change the position of the vertical banner
function checkAdvertisingHorizontal() {
	if ($('advertising_horizontal').getStyle('top') == '-5px') {
		$('advertising_vertical').setStyle({top: '-58px'});
	} 
}

// determine if a fulltext search form may be submitted
// formname must be explicitely given as parameter
function checkSearchInput(formname) {
	f=document.forms[formname];
	// trim the search term
	f.elements['searchterm'].value = f.elements['searchterm'].value.replace(/^\s*|\s+$/g, '');
	// if empty, the form may not be submitted
	return (f.elements['searchterm'].value != '');
}

function addBuddiesToRecipients() {
  buddies = window.document.getElementById('buddyform').elements['buddyname[]'];
  var recipients = "";
  var komma = "";
  if(window.document.getElementById('buddyform').elements['recipient'].value.length > 0) {
    recipients = window.document.getElementById('buddyform').elements['recipient'].value;
    komma = ",";
  }

	for(i=0;i<buddies.length;++i)
	{
    if(i > 0 && buddies[i].checked && ( recipients.indexOf( buddies[i].value ) < 0 ) ) {
      recipients += komma+buddies[i].value;
      komma = ",";
    }
  }
  window.document.getElementById('buddyform').elements['recipient'].value = recipients;
}

/* helper function: wait for x milliseconds */
function waitNMsec(msecs)
{
  var start = new Date().getTime();
  var cur = start
  while(cur - start < msecs)
  {
    cur = new Date().getTime();
  }
}

/* toggles one guestbook entry on or off */
function toggleGBEntry(ix)
{
	Element.toggle('divgb' + ix);
	Element.toggle('imgtagplus' + ix);
	Element.toggle('imgtagminus' + ix);
}



// Submits images from an iframe and waits for upload completion
function submitImages()
{
  var hasStage = false;
  var hasDetail = false;
  var hasAvatar = false;
  // find out which fields we have to cover

  var iframe_form_id = '';

  if(window.img_stage_fileform)
  {
    hasStage = true;
    iframe_form_id = 'img_stage_fileform';
  }
  if(window.img_detail_fileform)
  {
    hasDetail = true;
    iframe_form_id = 'img_detail_fileform';
  }
  if(window.img_avatar_fileform)
  {
    hasAvatar = true;
    iframe_form_id = 'img_avatar_fileform';
  }

	iframeObjs = window.frames;
	if(_IE6)
	{
		iframeObjs = new Array();

		if(hasStage) iframeObjs.push(window.img_stage_fileform);
		if(hasDetail) iframeObjs.push(window.img_detail_fileform);
		if(hasAvatar) iframeObjs.push(window.img_avatar_fileform);
	}

	for(i=0;i<iframeObjs.length;++i)
	{
	  // TODO: check if all iframes are upload frames (check name like _fileform)
	  ifr = iframeObjs[i];
    ifrd = ifr.document;
    if(ifrd)
 	  {
    	indicateProgress(ifr);
    	ifrd.forms[0].submit();
    }
    else
    {
   	  alert("No window.img_detail_fileform.document nr."+i);
    }
	}



	/*
	// wait for all screens to finish
	// this is a string like 11111 that will hopefully be reduced to an empty string
	pendingUploads = new Array();
    for(i=0;i<iframeObjs.length;++i)
    {
      pendingUploads[i] = "1";
    }

	while(pendingUploads.join('') != '')
    {
      for(i=0;i<iframeObjs.length;++i)
      {
	    ifr = iframeObjs[i];
        ifrd = ifr.document;
        if(ifrd)
  	    {
  	      if(ifr.uploadsuccessful)
  	      {
  	        alert(i+" ist fertig.");
  	      	pendingUploads[i] = '';
  	      }
  	    }
      }
    }
    */
  /*
  // wait for their content to refresh. This means that they were either successfull or failed, at least they're done loading
  if(hasStage && hasDetail)
    while(!window.img_stage_fileform.document || !window.img_detail_fileform.document) { };
  if(hasStage)
    while(!window.img_stage_fileform.document) { };
  if(hasDetail)
    while(!window.img_detail_fileform.document) { };
  if(hasAvatar)
    while(!window.img_avatar_fileform.document) { };
  */

}

// call only from iframe!
function indicateProgress(iframewindow)
{
  ue = iframewindow.document.getElementById('uploadElement');
  if(ue) {
    if(ue.value != "") {
     iframewindow.document.getElementById('progressIcon').style.display='block';
     iframewindow.document.getElementById('uploadElement').style.marginLeft='-2000px';
    }
  }
}


/* BEGIN roundabout functions */
var px=0;
var posx=0;
var MMA=280; // movement margin
var MAB=70;
var scrollAction;
function doRoundaboutScroll()
{
	//ow = document.getElementById('o').getElementsByTagName('span')[0].offsetWidth; // width of an image in the roundabout
	ow = document.getElementById('o').getElementsByTagName('div')[0].offsetWidth; // width of an image in the roundabout
	ol = document.getElementById('did').offsetLeft;
	speed = 0;

	pxnorm = (posx - ol); // rel. zum elementbeginn
	if(px > ow) {
		// beim rechtsscrollen raus
		roundaboutAddImageToRight();
		px = 0;
		}

	if(pxnorm <MMA)
	{
		speed = Math.ceil((MMA-pxnorm) / MAB);
		if(px>0)
		{
			 px -= speed;
		}
		else
		{
			roundaboutAddImageToLeft();
			px = ow;
		}
	}
	else if(pxnorm > (800-MMA))
	{
		speed = Math.ceil((pxnorm-(800-MMA)) / MAB);
		if(px<1400) px += speed;
	}
	ce = document.getElementById('cid');
	ce.style.left = (px * (-1))+"px";

}

function roundaboutAddImageToRight()
{
	// when scrolling right: put first element last
	oo = document.getElementById('o');
	moveSibling = oo.firstChild;
	//destSibling = oo.lastChild;
	oo.appendChild(moveSibling);
}

function roundaboutAddImageToLeft()
{
	// when scrolling left: put last element first
	oo = document.getElementById('o');
	destSibling = oo.firstChild;
	moveSibling = oo.lastChild;
	oo.insertBefore(moveSibling,destSibling);
}

function startScroll(e)
{
	if (!e) var e = window.event;
	if (e.pageX) posx = e.pageX;
	else if (e.clientX)
	{
		posx = e.clientX + document.body.scrollLeft	+ document.documentElement.scrollLeft;
	}
	clearInterval(scrollAction);
	scrollAction = setInterval("doRoundaboutScroll()", 5);
}

function stopScroll()
{
	clearInterval(scrollAction);
}
/* END roundabout functions */



// globale Browser/OS Variablen definieren
_DOM=false; _All=false; _NS4=false; _NS6=false; _NS7=false; _OP=false; _IE4=false; _IE5=false; _IE6=false; _NIE7=false; _OtherBrowser=false; _Mac=false; _Win=false; _OS2=false;

// Browser/OS Variablen setzen
function CheckBrowser(){
var navAgent=navigator.userAgent.toLowerCase();
var appVer=navigator.appVersion.toLowerCase();
var versMinor=parseFloat(appVer);
var versMajor=parseInt(versMinor);
_Mac=(navAgent.indexOf("mac")!=-1);
_Win=((navAgent.indexOf("win")!=-1)||(navAgent.indexOf("16bit")!=-1));
_OS2=(navigator.platform=="OS/2")?true:false;
_All=(document.all)?true:false;
_DOM=(document.getElementById)?true:false;
_OP=(window.opera)?true:false;
_SAFARI=(navAgent.indexOf('safari')!=-1)?true:false;
var iePos=appVer.indexOf('msie');
if (iePos!=-1){
     versMinor=parseFloat(appVer.substring(iePos+5,appVer.indexOf(';',iePos)));
     versMajor=parseInt(versMinor);}
nav6Pos=navAgent.indexOf('netscape6');
nav7Pos=navAgent.indexOf('netscape/7');
if (nav6Pos!=-1){
     versMinor=parseFloat(navAgent.substring(nav6Pos+10));
     versMajor=parseInt(versMinor); }
var netsc=((navAgent.indexOf('mozilla')!=-1) && (navAgent.indexOf('spoofer')==-1) && (navAgent.indexOf('compatible') == -1)
         && (navAgent.indexOf('opera')==-1) && (navAgent.indexOf('webtv')==-1));
_NS4=(document.layers)?true:false;
_NS6=(netsc&&versMajor==6);
_NS7=(netsc);
var msie=(iePos!=-1);
_IE4=(msie&&versMajor==4);
_IE5=(msie&&versMajor==5);
_IE6=(msie&&versMajor==6);
_IE7=(msie&&versMajor==7);
_OtherBrowser=(!_NS4&&!_NS6&&!_OP&&!_IE4&&!_IE5&&!_IE6);
}

CheckBrowser();

//if(_NS7 || _NS6) document.write('<link rel="stylesheet" href="/css/stylens.css" type="text/css">');
if(_IE5 || _IE6) document.write('<link rel="stylesheet" href="/css/styleie.css" type="text/css">');
if(_IE7) document.write('<link rel="stylesheet" href="/css/styleie7.css" type="text/css">');
if(_SAFARI) document.write('<link rel="stylesheet" href="/css/stylesafari.css" type="text/css">');


// where is thie function called?
function changeBg() {
	this.style.color='white';
}


//input field eingabebegrenzung:
//Tells the check function whether to throw an error or not
var over = false;
function chars_left(max, messagearea, left, text) {
  eval('eingabe = document.my_form.'+messagearea+'.value');
  current = eingabe.length;

  //How many left?
  var chars_left = max - current;
  //Over the limit or not?
  if(chars_left < 0) {
    //Over the limit
    over = true;
    var chars_left_positive = chars_left * -1;
    document.getElementById(left).innerHTML = "<span class='warnarea'>(" + chars_left_positive + "</span>";
    document.getElementById(text).innerHTML = "<span class='warnarea'> Zeichen zuviel!)</span>";
  }
  else {
    //Reset
    over = false;
    document.getElementById(left).innerHTML = "(" + chars_left;
    document.getElementById(text).innerHTML = " Zeichen)";
  }
}
function chars_left_id(max, messagearea, left, text) {
  eingabe = $(messagearea).value;
  current = eingabe.length;

  //How many left?
  var chars_left = max - current;
  //Over the limit or not?
  if(chars_left < 0) {
    //Over the limit
    over = true;
    var chars_left_positive = chars_left * -1;
    $(left).innerHTML = "<span class='warnarea'>(" + chars_left_positive + "</span>";
    $(text).innerHTML = "<span class='warnarea'> Zeichen zuviel!)</span>";
    if ($('windowbuttons')) {
        $('windowbuttons').style.display='none';
    }
  }
  else {
    //Reset
    over = false;
    $(left).innerHTML = "(" + chars_left;
    $(text).innerHTML = " Zeichen)";
    if ($('windowbuttons')) {
        $('windowbuttons').style.display='block';
    }
  }
}

// documentation please!
function check() {
 	if($('warning')) {
 		if(over == true) {
      $('warning').show();
      return false;
    }
    else {
      $('warning').hide();
      return true;
    }
  }
}


// documentation please!
var swfu;
var swfu2;
window.onunload = function () {
}

var W3CDOM = (document.createElement && document.getElementsByTagName);

// documentation please!
function init() {
  if (!W3CDOM) return;
  var fakeFileUpload = document.createElement('div');
  fakeFileUpload.className = 'fakefile';
  fakeFileUpload.appendChild(document.createElement('input'));
  var image = document.createElement('img');
  image.src='/img/layout/button_select.gif';
  fakeFileUpload.appendChild(image);
  var x = document.getElementsByTagName('input');
  for (var i=0;i<x.length;i++) {
    if (x[i].type != 'file') continue;
    if (x[i].getAttribute('noscript')) continue;
    if (x[i].parentNode.className != 'fileinputs') continue;
    x[i].className = 'file hidden';
    var clone = fakeFileUpload.cloneNode(true);
    x[i].parentNode.appendChild(clone);
    x[i].relatedElement = clone.getElementsByTagName('input')[0];
    if (x[i].value) {
      x[i].onchange();
    }
    x[i].onchange = x[i].onmouseout = function () {
      this.relatedElement.value = this.value;
    }
  }
}


/* TODO: clean up these functions! (ara - > hfr) */
/* Tabs */
/* http://actsasflinn.com/Ajax_Tabs/index.html */
function tabselect2(tab, controlname) {
  var tablist = $(controlname).getElementsByTagName('li');
  var nodes = $A(tablist);
  var lClassType = tab.className.substring(0, tab.className.indexOf('-') );

  nodes.each(function(node){
    if (node.id == tab.id) {
      tab.className=lClassType+'-selected';
      if(tab.blur)
      	tab.blur();
    } else {
      node.className=lClassType+'-unselected';
    };
  });

}

function tabselect(tab) {
  return tabselect2(tab, 'tabcontrol1');
}

function tabselect3(tab) {
  return tabselect2(tab, 'tabcontrol3');
}

function paneselect2(pane, controlname) {
  var panelist = $(controlname).getElementsByTagName('li');
  var nodes = $A(panelist);

  nodes.each(function(node){
    if (node.id == pane.id) {
      pane.className='pane-selected';
    } else {
      node.className='pane-unselected';
    };
  });
}

function paneselect(pane) {
  return paneselect2(pane, 'panecontrol1');
}

function paneselect3(pane) {
  return paneselect2(pane, 'panecontrol3');
}

function loadPane(pane, src) {
  //if (pane.innerHTML=='' || pane.innerHTML=='<img alt="Wait" src="/img/layout/spinner.gif" style="vertical-align:-3px" /> Loading...') {
   reloadPane(pane, src);
  // }
}

function reloadPane(pane, src) {
  new Ajax.Updater(pane, src, {asynchronous:1, evalScripts:true});
  updateIVW(src);
}

/* EOF Tabs */


function toggleElement(was, master) {

	//erstmal alle Elemente mit der Klasse .sublist schliessen
	$$('.sublist').each(Element.hide);

	var elm = document.getElementsByClassName('level1');
	for (var i=0; i<elm.length; i++) {
		elm[i].style.color = '#A59B9A';
		elm[i].style.backgroundColor='#F2F2F2';
	}

	//und dann das richtige oeffnen
	Element.show(was);

	$(master).style.color = '#000';
	$(master).style.backgroundColor='#e5e5e5';
    updateIVW(was);
}

function testtest() {
	var list = document.getElementById('vertnav');
	var entries = list.getElementsByTagName('li');
	for (i = 0; i < list.length; i++) {
		list[i].style.visibility = visible;	
	}
}

// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/* Funktion zum Ermitteln der Kreisposition vom Fadenkreuz im Listenerstellprozess */

function returnPosition() {
	document.forms['my_form'].scale1.value = Math.round(( $('kreis').x - $('skala').offsetLeft - $('kreis').width) / 18.5);
	/*document.forms['my_form'].scale2.value = Math.abs(Math.round(( $('kreis').y + 73 - $('kreis').height - 14 - $('skala').offsetTop ) / 10.6) -10 );*/
	document.forms['my_form'].scale2.value = Math.abs(Math.round(( $('kreis').y + 73 - $('kreis').height - 14 - $('skala').offsetTop ) / 10.6) -12 );
}


// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/* Funktionen zum automatischen Aendern des Titels beim Aendern der Rubrik im Select */

//Liste erstellen
var curRubrik; // store the current rubrik value for the onChange event
function change_rubrik() {
	oldRubrikLength = getRubrikWord(curRubrik).length;
	titleField = document.forms['my_form'].elements["title"];
	curTitle = titleField.value;
	if (oldRubrikLength>0) rest = curTitle.substring(oldRubrikLength);
	else rest = curTitle
	newRubrik = getRubrik();
	newRubrikWord = getRubrikWord(newRubrik);
	newTitle = newRubrikWord + rest;
	titleField.value = newTitle;
	curRubrik = newRubrik;
}

function change_title(e) {
	if (!e) var e = window.event;
	keyCode = e.which;
	if(!keyCode) keyCode = e.keyCode;
	if(keyCode != 37 && keyCode != 39) { // left/right
		titleField = document.forms['my_form'].elements["title"];
		curTitle = titleField.value;
		setTimeout("_doChangeTitle(\""+escape(curTitle)+"\");", 10);
	}
}
function _doChangeTitle(oldTitle) {
	oldTitle = unescape(oldTitle);
	ru = getRubrik();
	rw = getRubrikWord(ru);
	rl = rw.length;
	//titleField = document.my_form.elements["title"];
	titleField = document.forms['my_form'].elements["title"];
	curTitle = titleField.value;
	if(curTitle.substring(0,rl) != rw) {
		// deny title alteration
		titleField.value = oldTitle;
	}
	curTitle = titleField.value;
}
function getRubrik() {
	//alert(getRubrik.caller);
	//ru = document.my_form.elements['rubrik'];
	ru = document.forms['my_form'].elements['rubrik'];
	ruval = ru.options[ru.selectedIndex].value;
	return ruval;
}
function getRubrikWord(rubrikValue) {
	if(rubrikValue=="") {
		return ""
	} else {
		return rubrikValue.split("|")[0];
	}
}


function check_length(my_form,description,maxLength) {
	if (my_form.description.value.length >= maxLength) {
		// Reached the Maximum length so trim the textarea
		my_form.description.value = my_form.description.value.substring(0, maxLength);
	} else {
		// Maximum length not reached so update the value of my_text counter
		my_form.text_num.value = maxLength - my_form.description.value.length;
	}
}

/*
//input field eingabebegrenzung:
//Tells the check function whether to throw an error or not
var over = false;
function chars_left(max, messagearea, left, text) {
	fieldval = safeElementValueGet(messagearea);
  var current = fieldval.length;
          //How many left?
          var chars_left = max - current;
          //Over the limit or not?
          if(chars_left < 0)
          {
                  //Over the limit
                  over = true;
                  var chars_left_positive = chars_left * -1;
                  $(left).innerHTML = "<span class='warnarea'>(" + chars_left_positive + "</span>";
                  $(text).innerHTML = "<span class='warnarea'> Zeichen zuviel!)</span>";
          }
          else
          {
                  //Reset
                  over = false;
          				$(left).innerHTML = "(" + chars_left;
          				$(text).innerHTML = " Zeichen)";
          }

  }
  */



function checkChars(max, messagearea, left, text) {
	fieldval = safeElementValueGet(messagearea);

	// var current = document.getElementById(messagearea).value.length;
	var current = fieldval.length;
	var chars_left = max - current;
	/*
	document.getElementById(left).innerHTML = "(" + chars_left;
	document.getElementById(text).innerHTML = " Zeichen)";
	*/
	$(left).innerHTML = "(" + chars_left;
	$(text).innerHTML = " Zeichen)";
}

// safe element getter for text function:
// 1. textareas don't have a value - we get their innerText instead
// 2. getting an element by id "description" or "title" in IE6 or 7 gets the meta tag instead. We grab the textarea instead
function safeElementValueGet(elementName)
{
	// test if the element is named "description"
	if(elementName == 'description' || elementName == 'title')
	{
		descrElems = document.getElementsByName(elementName);
		fieldelem = descrElems[0];
		if(fieldelem.tagName.toLowerCase() == 'meta')
		{
			// get the last of these elements, just like Firefox does
			fieldelem = descrElems[descrElems.length-1];
		}
	}
	else
	{
		fieldelem = $(elementName);
	}

	if(fieldelem.tagName.toLowerCase()=='textarea' && _IE6)
	{
		fieldval = fieldelem.innerText;
	}
	else
	{
		fieldval = fieldelem.value;
	}
	return fieldval;
}


// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/* Funktionen zum Initialisieren von Formularseiten im Popup */

function initStep1Success() {
	//Drag einschalten

	var mydrag = new Draggable('lightbox', {handle:'dragger'});
    updateIVW('formstep1');
	//SelectBox initialisieren
	curRubrik = getRubrik();
	change_rubrik();

	//Laenge der Eingabefelder ueberpruefen
	checkChars(70, 'title', 'left1', 'text1');
	checkChars(350, 'description', 'left2', 'text2');

	showLate();
}

function initStep1aSuccess() {
	//Drag einschalten
	var mydrag = new Draggable('lightbox', {handle:'dragger'});
    updateIVW('formstep1a');
	//SelectBox initialisieren
	curRubrik = getRubrik();
	change_rubrik();

	//Laenge der Eingabefelder ueberpruefen
	checkChars(70, 'title', 'left1', 'text1');

	//Sichtbarkeit von Editorlisten setzen
	setVisibilityOfListType();

	showLate();
}
function initStep1bSuccess() {
	//Drag einschalten
	var mydrag = new Draggable('lightbox', {handle:'dragger'});
    updateIVW('formstep1b');
	showLate();
}
function initStep1cSuccess() {
	//Drag einschalten
	var mydrag = new Draggable('lightbox', {handle:'dragger'});
    updateIVW('formstep1c');
	//Fadenkreuz
	new Draggable('kreis',{ snap: function(x,y) { return[ x<200 ? (x > 15 ? x : 15 ) : 200, y<119 ? (y > 13 ? y : 13) : 119]; }, revert:false });

	//Laenge der Eingabefelder ueberpruefen
	checkChars(350, 'description', 'left2', 'text2');

	showLate();
}

function initStep2Success() {
	//Drag einschalten
	var mydrag = new Draggable('lightbox', {handle:'dragger'});
	//init();
    updateIVW('formstep2');
	checkChars(50, 'img_stage_copyright', 'left1', 'text1');
	checkChars(350, 'img_stage_description', 'left2', 'text2');
	checkChars(50, 'img_detail_copyright', 'left3', 'text3');
	checkChars(350, 'img_detail_description', 'left4', 'text4');

	showLate();
}
function initStep2userSuccess() {
	//Drag einschalten
	var mydrag = new Draggable('lightbox', {handle:'dragger'});
	//init();
    updateIVW('formstep2user');
	checkChars(50, 'img_stage_copyright', 'left1', 'text1');
	checkChars(350, 'img_stage_description', 'left2', 'text2');

	showLate();
}
function initStep2CatSuccess() {
	//Drag einschalten
	var mydrag = new Draggable('lightbox', {handle:'dragger'});
	//init();
    updateIVW('formstep2Cat');
	showLate();
}
function pickFrameForImageCat()
{
  var value=document.getElementById('rubrik').value;
  value=value.substring(value.indexOf('|')+1);
  var IFs = top.document.getElementsByTagName("IFRAME");
  // change the content of the imagebrowse iframe
  if(typeof(IFs['img_list']) == 'undefined')
  {
  	// Safari browser
  	top.frames['img_list'].location.href = '/listedit/imagespercat/'+value;
  }
  else
  {
  	// Non-Safari browsers
  	IFs['img_list'].src='/listedit/imagespercat/'+value;
  }
}

function initStep3Success() {

	//Drag einschalten
	var mydrag = new Draggable('lightbox', {handle:'dragger'});
    updateIVW('formstep3');
	if(document.forms['my_form'])
	{
	  // These functions shall not be called when in preview mode.
	  if($('Keywords'))
	  	$('Keywords').focus();

	  //Den Suche-Button initial deaktivieren
	  $('dsearch').disable();
	}
	showLate();
}

function initStep3BonusSuccess() {

	//Drag einschalten
	var mydrag = new Draggable('lightbox', {handle:'dragger'});
	updateIVW('formstep3Bonus');
	showLate();
}

/*
 * documentation please
 */
function setTheFocus() {
	window.setTimeout('document.my_form.Keywords.focus()', 300);
}

function initStep3SearchSuccess() {
	//Drag einschalten
	var mydrag = new Draggable('lightbox', {handle:'dragger'});
    updateIVW('formstep3Search');
	showLate();
}

function initStep3ListSuccess() {
	var mydrag = new Draggable('lightbox', {handle:'dragger'});
    updateIVW('formstep3List');
	showLate();
}

function step3CommentOpener(index) {
  var showOpen=($('imgtagplus'+index).style.display=='inline' || $('imgtagplus'+index).style.display=='');
  $('imgtagplus'+index).style.display='none';
  $('imgtagminus'+index).style.display='none';
  $('div'+index).style.display='none';
  if (showOpen) {
    $('imgtagminus'+index).style.display='inline';
    $('div'+index).style.display='inline';
  } else {
    $('imgtagplus'+index).style.display='inline';
  }
  updateIVW('step3Comment');
}


function initBewertungSuccess() {
	$('lightbox').addClassName('bewertung');
	var mydrag = new Draggable('lightbox', {handle:'dragger'});
	updateIVW('bewertung');
}
function initKommentarSuccess() {
	$('lightbox').addClassName('kommentar');
	var mydrag = new Draggable('lightbox', {handle:'dragger'});
	updateIVW('Kommentar');
}
function initLoginSuccess() {
	$('lightbox').addClassName('loginpop');
	var mydrag = new Draggable('lightbox', {handle:'dragger'});
    updateIVW('Login');
	//Bitte so stehen lassen, der $('form_username')..-Kram funktioniert nicht!, HFR
	//document.login_form.form_username.focus();

	//Event.observe('lightbox', 'keypress', function(){ closeWindow(this) });

}

function initPlayerLightboxSuccessAudio() {
	$('lightbox').addClassName('audiopop');
	var mydrag = new Draggable('lightbox', {handle:'dragger'});
	updateIVW('Player');
}
function initPlayerLightboxSuccessVideo() {
	$('lightbox').addClassName('videopop');
	var mydrag = new Draggable('lightbox', {handle:'dragger'});
	updateIVW('PlayerVideo');
}

function initSendListSuccess() {
	$('lightbox').addClassName('sendlistpop');
	var mydrag = new Draggable('lightbox', {handle:'dragger'});
	updateIVW('Send');
}

/*
 * general initialization function for already opened lightboxes
 * adapt height and width, make draggable
 * the lightbox id must be 'lightbox', the draggable area must have the id 'dragger'
 */
function initCustomLightbox(lWidth, lHeight, doMakeDraggable) {
	document.getElementById('lightbox').style.height=lHeight;
	$('lightbox').style.width=lWidth;
	$('windowcontent').style.height='auto';
	//$('lightbox').style.margin="-150px 0 0 -150px !important";
	if(doMakeDraggable == true) {
		new Draggable('lightbox', {handle:'dragger'});
	}
}

/*
function closeWindow(obj) {
	if (!e) var e = this.event;
	keyCode = e.which;
	if(!keyCode) keyCode = e.keyCode;

	alert(keyCode);

	debugger;
	alert(obj.keyCode);
}
*/
function initRegistrationSuccess() {
	var mydrag = new Draggable('lightbox', {handle:'dragger'});
	updateIVW('Registration');
}

function activateButton() {

	//alert(document.my_form.Keywords.value);

	if(document.my_form.Keywords.value != "") {
		$('dsearch').enable();
		$('dsearch').removeClassName('deactivated');
		$('Keywords').focus();
	}

	else {
		$('dsearch').disable();
		$('dsearch').addClassName('deactivated');
		$('Keywords').focus();
	}

}

function doSearchButton(evt) {
  if (evt.keyCode == 13) {
    document.my_form.func.value='searchItem';
    var x = new Ajax.Updater('lightbox', '/listedit', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this) });
    updateIVW('listedit');
    return false;
  }
}

// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/* Funktionen fuers Bewerten */

function mouseOverStar(star) {
	if($F('isSetStars')== '0') {
		//alle Bilder links des aktuellen einlesen
		var bilder = $(star).previousSiblings();

		//array aufsplitten
		bilder.each(function(s) {
		  //alert (s.id);
		  s.src = "/img/layout/rating_star.gif";
		});
		//und das Bild tauschen ueber dem ich mich gerade befinde
		 $(star).src = "/img/layout/rating_star.gif";
	}
}
function mouseOutStar(star) {
	if($F('isSetStars')== '0') {
		//alle Bilder links des aktuellen einlesen
		var bilder = $(star).previousSiblings();

		//array aufsplitten
		bilder.each(function(s) {
		  //alert (s.id);
		  s.src = "/img/layout/rating_no.gif";
		});

		//und das Bild tauschen ueber dem ich mich gerade befinde
		 $(star).src = "/img/layout/rating_no.gif";
	}
}
function voteThis(star) {
	//akutelle setzen
	mouseOverStar(star);
	isSetStars = true;
	$('vote').value = $(star).readAttribute('value');
	$('isSetStars').value= '1';
	updateIVW('Vote');
}


// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/* BEGIN functions for editing form fields */

function makeTag(wert) {
	// IE6 has problems with wrong encodings in the JS file source code
	wert = wert.replace(/[^a-z0-9\-\xE4\xF6\xFC\xDF]+/ig," ");
	$('tags').value= wert;
}

function chars_id(wert) {
	var a = $('id_field').value.split(/,/g);

	if(a.length > 14) {
		$('left1').innerHTML = "(" + a.length;
	} else {
		wert = wert.replace(/[^a-z0-9\-\xE4\xF6\xFC\xDF]+/ig,",");
		$('id_field').value= wert;
	}
}


function showBusyIndicator() {
	updateIVW('BusyIndikator');
	Element.show("busyIndicator");
}
function hideBusyIndicator() {
	Element.hide("busyIndicator");
}


/* Wofuer?? */
function startCallback() {
   // make something useful before submit (onStart)
   return true;
}

function completeCallback(response) {
   // make something useful after (onComplete)
   $('nr').innerHTML = parseInt(document.getElementById('nr').innerHTML) + 1;
   $('r').innerHTML = response;
}
/* END Wofuer?? */


function setVisibilityOfListType() {
	var val=$('list_type').selectedIndex;
	switch (val) {
	  case 1 : {
		Element.show("newslist");
		Element.hide("promilist");
		break;
	  }
	  case 2 : {
		Element.hide("newslist");
		Element.show("promilist");
		break;
	  }
	  default : {
		Element.hide("newslist");
		Element.hide("promilist");
		break;
	  }
	}
}

function setVisibilityOfTypeSelect() {
  var val=$('rubrik').value;
  if (val.indexOf('21')>0) {  // 21 in the category of Bonus. Therefore we don't need a listtype selector
	Element.hide("list_type_combo");
    Form.Element.setValue('list_type_combo','sponsor');
  } else {
    Element.show("list_type_combo");
    if ($('list_type')=='sponsor') {
      Form.Element.setValue('list_type_combo','user');
    }
  }
}


/* Useroffice */

// put on or off all checkboxes of the same name
// the on/off value is copied from the field srcField
function toggleSelectAll(checkboxesName, srcField)
{
	newCBVal = (srcField.checked==true);
	allCheckboxes = document.getElementsByName(checkboxesName);
	for(i=0;i<allCheckboxes.length;++i)
	{
		allCheckboxes[i].checked = newCBVal;
	}
}
function toggleSelectAllPanes(pane,srcField)
{
	newCBVal = (srcField.checked==true);
	allCheckboxes = pane.getElementsByTagName('input');
	for(i=0;i<allCheckboxes.length;++i)
	{
		if (allCheckboxes[i].name.substring(0,4)=='chk_') {
			allCheckboxes[i].checked = newCBVal;
		}
	}
}

// control for the list actions dropdown in useroffice
function processListAction(action_name)
	{
		checkedLists=new Array();
		// get all checked elements
		allCheckboxes = document.getElementsByName('listcheck');
		for(i=0;i<allCheckboxes.length;++i)
		{
			if(allCheckboxes[i].checked == true)
			{
				checkedLists.push(allCheckboxes[i].value);
			}
		}
		checkedListsString = checkedLists.join(",");
		numCheckedLists = checkedLists.length;

		if(numCheckedLists > 0)
		{
			switch(action_name)
			{
				case '':
					return false;
					break;
				case 'delete':
						if(numCheckedLists == 1) text = "Sind Sie sicher, dass Sie die ausgew\xE4hlte Liste l\xF6schen m\xF6chten? Geben Sie bitte JA ein."+checkedListsString;
						else text = "Sind Sie sicher, dass Sie die "+numCheckedLists+" ausgew\xE4hlten Listen l\xF6schen m\xF6chten? Geben Sie bitte JA ein."+checkedListsString;

					//if(confirm(text))
					delword = prompt(text);
					if(delword == "JA")
					{
						// ##TODO: do delete
						//alert(checkedListsString);
						location.href='/deletelists/'+checkedListsString;
					}
					else if(delword=="")
					{
						// do nothing.
					}
					else
					{
						alert("Die Eingabe war nicht JA. Die Liste(n) werde(n) nicht gel\xF6scht.");
					}
					break;
				case 'print':

				// TODO: Problem: we lose the front controller here when not using something like url_for. But how can we pass the JS variables to the url_for?

					location.href='/listview/print/'+checkedListsString;
					break;
				case 'block':
						if(numCheckedLists == 1) text = "Sind Sie sicher, dass Sie die ausgew\xE4hlte Liste sperren m\xF6chten?";
						else text = "Sind Sie sicher, dass Sie die "+numCheckedLists+" ausgew\xE4hlten Listen sperren m\xF6chten?";

					//if(confirm(text))
					delword = confirm(text);
					if(delword) {
						location.href='/blocklists/'+checkedListsString;
					} else {
						// do nothing.
					}
					break;
				case 'unblock':
						if(numCheckedLists == 1) text = "Sind Sie sicher, dass Sie die ausgew\xE4hlte Liste entsperren m\xF6chten? Sie wird danach den Status 'in Arbeit' haben und nicht live geschaltet sein.";
						else text = "Sind Sie sicher, dass Sie die "+numCheckedLists+" ausgew\xE4hlten Listen entsperren m\xF6chten? Sie werden danach den Status 'in Arbeit' haben und nicht live geschaltet sein.";

					//if(confirm(text))
					delword = confirm(text);
					if(delword) {
						location.href='/unblocklists/'+checkedListsString;
					} else {
						// do nothing.
					}
					break;
			}
		}
		//Form.Element.setValue('listActions','');
	}


function showLate() {
	//alert(document.getElementsByClassName('showLate'));

	var buttons = document.getElementsByClassName('showLate')

	//array aufsplitten
	buttons.each(function(s) {
	  s.style.visibility = "visible";
	});
}

/*
prototypeUtils.js from http://jehiah.com/
Licensed under Creative Commons.
version 1.0 December 20 2005

Contains:
+ Form.Element.setValue()
+ unpackToForm()

*/

/* Form.Element.setValue("fieldname/id","valueToSet") */
Form.Element.setValue = function(element,newValue) {
    element_id = element;
    element = $(element);
    if (!element){element = document.getElementsByName(element_id)[0];}
    if (!element){return false;}
    var method = element.tagName.toLowerCase();
    var parameter = Form.Element.SetSerializers[method](element,newValue);
}

Form.Element.SetSerializers = {
  input: function(element,newValue) {
    switch (element.type.toLowerCase()) {
      case 'submit':
      case 'hidden':
      case 'password':
      case 'text':
        return Form.Element.SetSerializers.textarea(element,newValue);
      case 'checkbox':
      case 'radio':
        return Form.Element.SetSerializers.inputSelector(element,newValue);
    }
    return false;
  },

  inputSelector: function(element,newValue) {
    fields = document.getElementsByName(element.name);
    for (var i=0;i<fields.length;i++){
      if (fields[i].value == newValue){
        fields[i].checked = true;
      }
    }
  },

  textarea: function(element,newValue) {
    element.value = newValue;
  },

  select: function(element,newValue) {
    var value = '', opt, index = element.selectedIndex;
    for (var i=0;i< element.options.length;i++){
      if (element.options[i].value == newValue){
        element.selectedIndex = i;
        return true;
      }
    }
  }
}

function unpackToForm(data){
   for (i in data){
     Form.Element.setValue(i,data[i].toString());
   }
}

// TODO: could't this be done with the toggle function?
function changeValue(where) {
  if($F(where) == 0) {
    Form.Element.setValue(where,"1");
  }
  else {
    Form.Element.setValue(where,"0");
  }
}

// TODO: this function can probably be reduced to the new Efect line?
function moveRight() {
	var tochter = $('slide').immediateDescendants();

	tochter.each(function(s) {
	 // alert(s);
	});
	new Effect.Move('slide',{x : -670,y : 0 , duration:0.1});
}

/* BEGIN mail-notification window functions */
// show the top-right mail-notification window
function showTopNotifier()
{
  // $('topnotify').style.display='block';
  // new Effect.BlindDown('topnotify', {duration:2});
  new Effect.Opacity('topnotify',
  { duration: 1.0,
    transition: Effect.Transitions.linear,
    from: 0.0, to: 1.0,
    afterUpdate: function() { $('topnotify').style.display='block'; } });
  window.setTimeout("hideTopNotifier()", 10000);
}

// hide the top-right mail-notification window
function hideTopNotifier()
{
  new Effect.Opacity('topnotify',
  { duration: 1.0,
    transition: Effect.Transitions.linear,
    from: 1.0, to: 0.0,
    afterFinish: function() { $('topnotify').style.display='none'; } });
}

/* END mail-notification window functions */

/*
 * in case our lightbox does not close by having the rel=deactivate alone,
 * we will force it to close using the onmouseup=closeLightbox() attribute.
 */
function closeLightbox()
{
  // get current URL without page anchor
  currentUrl = window.location.href.replace(/\#.*$/,"");
  //$('lightbox').innerHTML = ''; // kill the lightbox content (try for windows media player, which did not work)
  window.setTimeout("if($('lightbox')) { window.location.href='"+currentUrl+"';}", 500);
}

/*
 * Windows media player objects will remain running even if their host HTML elements are killed.
 * We have to remove their embed elements to stop them playing.
 * This function is not used right now, instead we reload the page. Would be better, though.
 */
function killAudioVideoPlayers()
{
  lb=$('lightbox');
  allobjs = lb.getElementsByTagName('embed');
  for(i=0;i<allobjs.length;++i) {
    allobjs[i].remove();
  }
  allobjs = lb.getElementsByTagName('object');
  for(i=0;i<allobjs.length;++i)
  {
    allobjs[i].remove();
  }
}


// to avoid ie's flash content activation, the object tag must be set from outside the page.
// so the code is set via this function (http://msdn.microsoft.com/ieupdate)
function externWriteToDocument(string)
{
	document.write(string);
}

/*
 * documentation please
 */
  function clearTextField( currentField, defaultInput )
	{
	  if(document.getElementById(currentField).value == defaultInput)
	  {
	    document.getElementById(currentField).value = "";
	    document.getElementById(currentField).focus();
	  }
	}

/*
 * listview page: show the comment of listentries / or hide it
 *
 * idNo: the number of the elemets id (eg. 1 -> listComment1)
 * doDisplay: true=show, false=hide
 * ivwCount: true=do count, false=do not count
 */
  function showListComment(idNo, doDisplay, ivwCount)
  {
	// show / hide the comment
  	if(doDisplay == true)
  	{
  		$('listCommentRow'+idNo).style.display = ''; // show the table row
  		Effect.SlideDown('listComment'+idNo, {duration:0.5});
  		$('listCommentCollapse'+idNo).style.display = 'block';
  		$('listCommentExpand'+idNo).style.display = 'none';
  		if (ivwCount) 
  		{
  			updateIVW('CommentShow');
  		}
  	}
  	else
  	{
  		Effect.SlideUp('listComment'+idNo, {duration:0.5, idNo:idNo, afterFinish: function(){ $('listCommentRow'+this.idNo).style.display = 'none';} });
  		$('listCommentCollapse'+idNo).style.display = 'none';
  		$('listCommentExpand'+idNo).style.display = 'block';
  		if (ivwCount) 
  		{
  			updateIVW('CommentCollapse');
  		}
  	}
  	// fix the tables dimensions
  	if($('listEntryTable').style.tableLayout != "fixed")
  	{
  		if ($('titleColumn').offsetWidth > 0) {
  			// this line can not be interpreted by IE -> error: invalid argument // 23.07.08 jwinzer
			$('titleColumn').style.width = $('titleColumn').offsetWidth-3;
		}
		$('listEntryTable').style.tableLayout = "fixed";
	}
  }
