//var htmlpfad = "";
//var urlpfad = "http://eros.nikmedia.dynalias.com";

function save_pos(obj, user)
{
  var x = $("matchings_" + obj).style.left;
  var y = $("matchings_" + obj).style.top;  
  
  new Ajax.Request(urlpfad + htmlpfad + "/ajax/window_save_pos.php",{method:"post",parameters:"posx="+x+"&posy="+y+"&obj="+obj+"&user="+user});

  showz(obj);
}

function hideMessage(mess)
{
  $("mess_" + mess).style.display = "none";
}

function save_pos_start(x,y, obj)
{
   offx[obj] = x - posx[obj];
   offy[obj] = y - posy[obj];
   posx[obj] = x;
   posy[obj] = y;
  
   //var zi = $("matchings_" + obj).style.zIndex;
   
   zi = zi + 5;
   
   $("matchings_" + obj).style.zIndex = zi;
   
   showz(obj);
   //alert (zi);
   
  // posy[obj] = $("matchings_" + obj).style.top;
}

function HideOnly(wind)
{
  if($("matchings_"+wind))
  {
    var body = $("matchings_"+wind).parentNode;
    for(var i=0;i<body.childNodes.length;i++)
    {
      if(body.childNodes[i].id == "matchings_"+wind)
        body.removeChild(body.childNodes[i]);
    }
  }
}

function Hide(wind)
{
  if(!$("matchings_" + wind))
    return false;
  $("matchings_" + wind).style.display="none";
  new Ajax.Request(htmlpfad + "/ajax/matchings_hide.php", {method:"post",parameters:"obj="+wind});
}
var count = 1;
function Show(wind)
{
  new Ajax.Request(htmlpfad + "/ajax/matchings_hide.php", {method:"post",parameters:{obj:wind,on:1}});
  if($("matchings_" + wind))
  {
    $("matchings_" + wind).style.display="block";
  }
  else
  {
    var obj = document.getElementsByTagName('body')[0];
    var node = document.createElement('div');
    node.setAttribute('style','height:0px;width:0px;position:absolute;top:0;left:0');
    node.setAttribute('id','WindowLoad'+count);
    obj.appendChild(node);
    /* new Ajax.Request("/ajax/windows/window_load.php", {method:"post",evalScripts:true,parameters:{id:wind},onSuccess:function(t){
      document.getElementsByTagName('div')[document.getElementsByTagName('div').length-1].innerHTML = t.responseText;
      new Draggable("matchings_"+wind, {ghosting:false, revert:false,handle:"titel2"})
    }});	 */
    window.setTimeout('new Ajax.Updater("WindowLoad"+'+count+',htmlpfad + "/ajax/window_load.php",{method:"post",evalScripts:true,insertion:Insertion.bottom,parameters:{id:'+wind+'}});',250);
    count++;
  }
  window.setTimeout("tip.replace()",500);
}

function ShowOnly(wind)
{
  if($("matchings_" + wind))
  {
    $("matchings_" + wind).style.display="block";
  }
  else
  {
    var obj = document.getElementsByTagName('body')[0];
    var node = document.createElement('div');
    node.setAttribute('style','height:0px;width:0px;position:absolute;top:0;left:0');
    node.setAttribute('id','WindowLoad'+count);
    obj.appendChild(node);
    /* new Ajax.Request("/ajax/windows/window_load.php", {method:"post",evalScripts:true,parameters:{id:wind},onSuccess:function(t){
      document.getElementsByTagName('div')[document.getElementsByTagName('div').length-1].innerHTML = t.responseText;
      new Draggable("matchings_"+wind, {ghosting:false, revert:false,handle:"titel2"})
    }});	 */
    window.setTimeout("new Ajax.Updater('WindowLoad'+"+count+",htmlpfad + '/ajax/matchings_load.php',{method:'post',evalScripts:true,insertion:Insertion.bottom,parameters:{id:"+wind+"}});",250);
    count++;
  }
}

function minimize(obj)
{
  var bl;

  stat = $("fmain_" + obj).style.display;

  if (stat == "none")
  {
    $("fmain_" + obj).style.display="block";
    bl = 0;
  }
  else
  {
    $("fmain_" + obj).style.display="none";
    bl = 1;
  }
  
  new Ajax.Request(htmlpfad + "/ajax/matchings_minimize.php", {method:"post",parameters:"ob="+obj+"&stat="+bl});
}

function outline(id, bild)
{
 var img = id + '_img';
 
 //alert("Hallo");
 
 if(document.getElementById(id).style.display == 'none')
 {
  document.getElementById(id).style.display = 'block';
  
  if(document.getElementById(img)) 
  {
    document.getElementById(img).src = htmlpfad + '/images/layout/' + bild + '_l.png';
  }
 }
 else
 {
  document.getElementById(id).style.display = 'none';
  
  if(document.getElementById(img)) 
  { 
    document.getElementById(img).src = htmlpfad + '/images/layout/' + bild + '_r.png';
  }
 }
 
 if($("paarlink"))
 {
   if($("paarlink").innerHTML == "Wir möchten uns als Paar anmelden")
    $("paarlink").innerHTML = "Ich möchte mich alleine anmelden";
   else
    $("paarlink").innerHTML = "Wir möchten uns als Paar anmelden";
 }
}

function outline2(id, bild)
{
 var img = id + '_img';
 
 //alert("Hallo");
 
 if(document.getElementById(id).style.display == 'none')
 {
  document.getElementById(id).style.display = 'block';
  
  if(document.getElementById(img)) 
  {
    document.getElementById(img).src = htmlpfad + '/images/layout/' + bild + '_up_r.png';
  }
 }
 else
 {
  document.getElementById(id).style.display = 'none';
  
  if(document.getElementById(img)) 
  { 
    document.getElementById(img).src = htmlpfad + '/images/layout/' + bild + '_down_r.png';
  }
 }
 
 if($("paarlink"))
 {
   if($("paarlink").innerHTML == "Wir möchten uns als Paar anmelden")
    $("paarlink").innerHTML = "Ich möchte mich alleine anmelden";
   else
    $("paarlink").innerHTML = "Wir möchten uns als Paar anmelden";
 }
}

function showz(obj)
{
  //z1 = $("matchings_" + obj).style.zIndex;
  //$("f1").innerHTML = z1;
}

function Create(bname)
{
  Sortable.create(bname,
  {
    tag:'div',
    overlap:'vertical',
    constraint:false,
    handle:'handlepoint',
    onUpdate:function()
    { 
      Update(Sortable.serialize(bname) + "&vnam="+bname); 
    }
  })
}

function Create2(bname)
{
  Sortable.create(bname,
  {
    tag:'fieldset',
    overlap:'horizontal',
    constraint:false,
    handle:'handlepoint',
    onUpdate:function()
    { 
      Update(Sortable.serialize(bname) + "&vnam="+bname); 
    }
  })
}

function Update(parameters)
{
  new Ajax.Request(htmlpfad + '/ajax/start_boxen.php',{method:'post',parameters:parameters});
}

function test()
{
  alert("klappt");
}

function setBild(id, method, comment)
{
  var mpfad = htmlpfad + "/galerie/getImage.php?id=" + id + "&method=" + method;

/*
      $ret .= "<img src='$GLOBALS[html]/images/layout/delete.png' onClick='abort()' alt='Fenster schließen'><br>";
*/
  
  $("pfoto").src = mpfad;
  $("pfoto").onclick = function(){getBreite();increase();};
  $("pfoto").style.cursor = "pointer";
  $("mbig").style.display = "block";
  
    
  if (comment != "")
  {
    var ko = "<b><u>Kommentar:</u></b> ";
  }
  else
  {
    var ko = "";
  }

  $("mcontent").innerHTML = "<div style='font-size:10px;padding-bottom:10px'>" + ko + comment + "</div><img src='" + htmlpfad + "/galerie/getImage.php?id=" + id + "' />";
  
}
function setSchleierBild(id)
{
  $("mcontent").innerHTML = "<img src='" + htmlpfad + "/galerie/getImage.php?id=" + id + "'>";

  // Breite des Bildes ermitteln
  var breite = $("bi_" + id).value;

  // alert ("Breite : " + breite);
  if(breite > 600)
    breite = 600;
  var npos = Math.round((1000 - breite) / 2);
  
  //alert("Neue Position : " + npos);
  
  $("mbild").style.left = npos + "px";
  
  
}

function getBreite()
{
  //alert("Hallo");

  var breite = $("afoto").value;
 
  //alert(breite);
  var maxbreite = document.body.offsetWidth;
  if(isNaN(maxbreite))
  maxbreite = 1024;
  if(breite > maxbreite * 0.75)
  breite = maxbreite * 0.75;
 
  var npos = Math.round((maxbreite - breite) / 2);
  $("mbild").style.left = npos + "px";
  
  var obj = $("mbild").getElementsByTagName("img");
  //obj[1].width = breite;
}

function delMessage()
{
  $("ajaxMessage").innerHTML = "";
}

function radioValue(objs)
{
	for(var i=0;i<objs.length;i++) if(objs[i].checked == true) return objs[i].value;
	return false;
}

function gotoBestellung()
{
	var lz = radioValue(document.getElementsByName('gueltig'));
	if(lz == false)
	{
		alert('Sie müssen ein Premium Paket auswählen!');
		return;
	}
	location.href = '/userbereich/premium_bestellung.php?lz='+lz;
}

var centerObj = function(obj)
{
	if(typeof obj != "object")
		obj = $(obj);
	if(document.documentElement && document.documentElement.clientHeight)
  {
    var iHeight = document.documentElement.clientHeight;
    var iWidth = document.documentElement.clientWidth;
  }
  else if(document.body && document.body.clientHeight)
  {
    var iHeight = document.body.clientHeight;
    var iWidth = document.body.clientWidth;
  }
  else
  {
    var iHeight = window.innerHeight;
    var iWidth = window.innerWidth;
  }
  
  var height = obj.offsetHeight;
  var width = obj.offsetWidth;
  
  if(height < 400) height = 400;
  if(width < 600) width = 600;
  
  var top,left;
  
  if(height > iHeight)
	top = 0;
  else
	top = (iHeight - height) / 2;

  if(width > iWidth)
	left = 0;
  else
	left = (iWidth - width) / 2;
  
  //alert("iHeight: "+iHeight+"\nheight: "+height+"\ntop: "+top+"\niWidth: "+iWidth+"\nheight: "+width+"\ntop: "+left);
  
  obj.style.top = top+"px";
  obj.style.left = left+"px";
}
var highlighting;
function increase() 
{
    // Schleicher wird erstmal entfernt, deshalb Bild gleich auf sichtbar setzen
    abort();
    $('mbild').setStyle({display:'block'});
    //setTimeout('centerObj("mbild");',50);

    return;

    /*
    abort();
  var element = $('schleier')
  element.setStyle({display:'block'});
  theobject = document.getElementById('schleier');
  theobject.style.display="block";
  
  highlighting = setInterval(highlight.bind(null,theobject), 10);*/
}
 
function abort() 
{

    // Schleier erstmal entfernt, deshalb einfach nur Bild ausblenden
    $('mbild').setStyle({display:'none'});
    return;

  /*img = document.getElementById('schleier');
  img.style.display="none";
 
  img.style.MozOpacity = 0.0;
  img.style.KHTMLOpaciry = 0.0;
  
  $("mbild").style.display = "none";
  
  if (img.filters)
  { 
    img.filters.alpha.opacity = 0;
  }
  if(highlighting)
    clearInterval(highlighting);*/
}
 
function highlight(img) 
{
  // Maximale Transparenz = 50% 
  //alert("Wann erscheine ich wohl?");
 
  if (img.style.MozOpacity < 0.5) 
  {
    img.style.MozOpacity = parseFloat(img.style.MozOpacity) + 0.05;
  }
  else if (img.style.KHTMLOpacity < 0.5)
  {
  img.style.KHTMLOpacity = parseFloat(img.style.KHTMLOpacity) + 0.05;
  }
  else if (img.filters && img.filters.alpha.opacity < 50)
  {
    img.filters.alpha.opacity += 10;
    //alert(img.filters.alpha.opacity); 
  }
  else if (window.highlighting)
  {
     clearInterval(highlighting);
    //alert("Element");
    //$("mbild").style.display = "block";
	//$("mbildbg").style.display = "block";
    Effect.Appear('mbild');
	setTimeout('centerObj("mbild");',50);
  }
}

posx = new Array();
posy = new Array();
offx = new Array();
offy = new Array();

var zi = 1000; 

function zahlArt(num)
{
	if((num == 1) && document.getElementsByName('lz')[0].value == 6)
	{
		document.getElementsByName('zahlung')[1].checked = true;
		alert('Bei einem 6 Monats Abo kann nur per Paypal gezahlt werden.');
		return;
	}
  if (num == 1)
  {
    //$("einzug").style.display = "none";
    //Effect.BlindUp("einzug");
    //var preis = getPreis();
    //$("betrag").innerHTML = getPreis().toFixed(2) + " &euro;";
    
    //$("ueberweisung").style.display = "block";
    $("zahlw").value = "ueberweisung";
    //alert('Bearbeitungszeit bei Überweisung: Nach Zahlungseingang max. 2 Werktage');
	$("verz").innerHTML = "<small>Freischaltung sofort nach Zahlungseingang</small>";
  }
  else if(num == 2)
  {
    //Effect.BlindDown("einzug");
    //$("einzug").style.display = "block";
    
    //var rpreis = (getPreis() -(getPreis() / 100 * rabatt));
    
    //$("betrag").innerHTML = rpreis.toFixed(2) + " &euro;";
    
    //$("ueberweisung").style.display = "none";
    //$("zahlw").value = "einzug";
	$("verz").innerHTML = "<small><b style='margin-left:100px'>Sofortige Freischaltung</b></small>";
  }
  else if(num == 3)
  {
     // $("einzug").style.display = "none";

      //$("ueberweisung").style.display = "none";
      $("zahlw").value = "paypal";

      $("verz").innerHTML = "<small><b>Sofortige Freischaltung.</b></small>";
  }
}

function xlink(l) 
{
  document.location.href = l;
}

function Eigenschaft_Add(id)
{
  Show(3);
  new Ajax.Updater("ajaxMessage", htmlpfad + "/ajax/Add_Eigenschaft.php",{method:"get",parameters:{id:id},evalScripts:true});
  //$("ajaxMessage").innerHTML = "<img src='/images/layout/delete.png' onClick='return delMessage()' style='cursor:pointer;' align='right'><br>Test";
  //$("ajaxMessage").style.display = "block";
}

// Suchagenten

var name,id;
function save()
    {
      name = ($("matching_name").value) ? $("matching_name").value : name;
      var param = "name="+name;
      param += "&finde="+$("matching_finde").value;
      param += "&von="+$("matching_alter_von").value;
      param += "&bis="+$("matching_alter_bis").value;
      param += "&umkreis="+$("matching_umkreis").value;
      param += "&id="+id;
    param += "&email="+$("matching_email").checked;
      new Ajax.Request(htmlpfad + "/ajax/matchings_save.php",{method:"post",parameters:param});
      $("matchings_name").innerHTML = "Name: <span id=\"matching_sname\">"+$("matching_name").value+"</span><a href=\"#\" onclick=\"Edit()\"><img src=\"" + htmlpfad + "/images/layout/Pencil.png\" alt=\"Edit\" title=\"Edit\" border=\"0\" /></a><a href=\"#\" onclick=\"Edit_new()\"><img src=\"" + htmlpfad + "/images/layout/new.png\" alt=\"Neu\" title=\"Neu\" border=\"0\" /></a></a>";
      get(id);
    }
  
  function mdelete()
  {
    var anz = $("matching_anzeigen").length;
    
    new Ajax.Request(htmlpfad + "/ajax/matchings_delete.php",{method:"post",parameters:{del:$F("matching_anzeigen")},onSuccess:function(t){get("latest");}})
    
    //alert(anz);
    
    if (anz == 1)
    {    
      $("a_del").style.display = "none";
      $("a_edit").style.display = "none";
      $("a_start").style.display = "none";
    }  
  }

  function save_new()
    {
      name = ($("matching_name").value) ? $("matching_name").value : name;
      var param = "name="+name;
      param += "&finde="+$("matching_finde").value;
      param += "&von="+$("matching_alter_von").value;
      param += "&bis="+$("matching_alter_bis").value;
      param += "&umkreis="+$("matching_umkreis").value;
    param += "&email="+$("matching_email").checked;
      new Ajax.Request(htmlpfad + "/ajax/matchings_save_new.php",{method:"post",parameters:param,onSuccess: function(t){
        if(t.responseText=="toomuch")
          alert("Sie können keine weiteren Matchings speichern!");
        if(t.responseText=="false")
          alert("Fehler beim Speichern des Matchings!");
      get("latest");
      }});
      $("matchings_name").innerHTML = "Name: <span id=\"matching_sname\">"+$("matching_name").value+"</span><a href=\"#\" onclick=\"Edit()\"><img src=\"" + htmlpfad + "/images/layout/Pencil.png\" alt=\"Edit\" title=\"Edit\" border=\"0\" /></a><a href=\"#\" onclick=\"Edit_new()\"><img src=\"" + htmlpfad + "/images/layout/new.png\" alt=\"Neu\" title=\"Neu\" border=\"0\" /></a></a>";
    }
  
    function get_eigenschaften(mid)
    {
      new Ajax.Request(htmlpfad + "/ajax/matchings_get_eigenschaften.php",{method:"get",parameters:{id:mid},onSuccess: function(t){
        $("matching_eigenschaften").innerHTML = t.responseText;
      }});
    }
  
    function delete_eigenschaft(eid)
    {
      new Ajax.Request(htmlpfad + "/ajax/matchings_delete_eigenschaft.php",{method:"post",parameters:{id:eid},onSuccess:function(){get_eigenschaften(id)}});
    }
    
  function add_eigenschaft(eid)
    {
      new Ajax.Request(htmlpfad + "/ajax/matchings_add_eigenschaft.php",{method:"post",parameters:{id:eid,matching:id},onSuccess:function(){get_eigenschaften(id)}});
    }
  
  var datacache = 0;
    function get(gid)
    {
      new Ajax.Request(htmlpfad + "/ajax/matchings_get.php",{method:"get",parameters:"id="+gid,onSuccess: function(t){
      var arg = t.responseText.split("|");
      //name = arg[1];
      id = arg[0];
      //$("matching_sname").innerHTML = arg[1];
      //$("matching_anzeigen").innerHTML = arg[2];
    if(datacache > 0)
    {
      add_eigenschaft(datacache);
      datacache = 0;
    }
    if(arg[2])
    {
      var obj = document.getElementById('matching_anzeigen');
      for(var i=0;i<obj.childNodes.length;i++)
      {
        obj.removeChild(obj.childNodes[i]);
      }
      obj.innerHTML = "";
      var arr = preg_match_all(arg[2],"<option value=\"(\\d+?)\">(.+?)<\/option>");
      var node,tnode;
      
      for(var ii=0;ii<arr.length;ii++)
      {
        node = document.createElement("option");
        node.setAttribute("value",arr[ii][1]);
        tnode = document.createTextNode(arr[ii][2]);
        node.appendChild(tnode);
        obj.appendChild(node);
      }
      
    }
    else
    {
      var node = document.createTextNode('--- Keine Suchagenten vorhanden ---');
      document.getElementById('matching_anzeigen').parentNode.replaceChild(node,document.getElementById('matching_anzeigen'));
    }
    //window.setTimeout("get_eigenschaften(id);",200);
      SelectedValue($("matching_anzeigen"),id);
      }});
    }

    function Edit()
    {
      $("matchings_name").innerHTML = "<input type=\"text\" name=\"matching_name\" id=\"matching_name\" value=\""+name+"\" style=\"width:100px\" /><a href=\"#\" onclick=\"save()\"><img src=\"" + htmlpfad + "/images/layout/Checked.png\" alt=\"Speichern\" title=\"Speichern\" border=\"0\" />";
    }
  
    function Edit_new()
  {
      $("matching_finde").selectedIndex = 0;
      $("matching_alter_von").selectedIndex = 0;
      $("matching_alter_bis").selectedIndex = 81;
      $("matching_umkreis").selectedIndex = 0;
    $("matching_email").checked = false;
      $("matchings_name").innerHTML = "<input type=\"text\" name=\"matching_name\" id=\"matching_name\" value=\"\" style=\"width:100px\" /><a href=\"#\" onclick=\"save_new()\"><img src=\"" + htmlpfad + "/images/layout/Checked.png\" alt=\"Speichern\" title=\"Speichern\" border=\"0\" />";
    $("matching_eigenschaften").innerHTML = "";
  }
  
    function SelectedValue(obj,value)
  {
      for(var i=0;i<obj.options.length;i++)
      {
        //obj[i].selected = false;
        if(obj[i].value == value)
        {
          obj[i].selected = true;
        }
      }
    }
  function preg_match_all(s,r)
  {
	var pattern = (preg_match_all.arguments.length >= 3) ? preg_match_all.arguments[2] : 'g';
    var regex1 = new RegExp(r,pattern);
    var regex2 = new RegExp(r);
    var hits = new Array();
    var tmp = s.match(regex1);
    for(var i=0;i<tmp.length;i++)
      hits[i] = tmp[i].match(regex2);
    return hits;
  }

/* ****** Adressbuch ****** */
    var adressbuch = function()
    {			
      this.favoriten = new Object();
      var fav = new Object();
      fav.array = new Array();
      fav.array[0] = new Array();
      fav.array[0][0] = "Meine Favoriten";
      fav.array[0][1] = new Array();
      fav.array[0]["load"] = false;
      fav.array[1] = new Array();
      fav.array[1][0] = "Ich bin Favorit von";
      fav.array[1][1] = new Array();
      fav.array[1]["load"] = false;
      fav.array[2] = new Array();
      fav.array[2][0] = "Meine Kontakte";
      fav.array[2][1] = new Array();
      fav.array[2]["load"] = false;
      
      this.agenten = new Object();
      var agt = new Object();
      agt.array = new Array();
      agt.load = false;
      
      /* Suchagentenliste ein- und ausblenden und AJAX Request */
      this.agenten.init = function()
      {
        if($("agenten_liste").style.display != "block")
        {
          $("agenten_liste").style.display = "block";
          $("agenten_icon").src = htmlpfad + "/images/layout/minus.gif";
          $("agenten_icon").alt = "-";
        }
        else
        {
          $("agenten_liste").style.display = "none";
          $("agenten_icon").src = htmlpfad + "/images/layout/plus.gif";
          $("agenten_icon").alt = "+";
        }
        if(agt.load == false)
        {
          new Ajax.Request(htmlpfad + "/ajax/getAgenten.php",{onSuccess:function(t){
            if(t.responseText == "xNE")
            {
              content = "Keine Suchagenten vorhanden";
            }
            else
            {
              var tmp = t.responseText.split("|");
              for(var i=0;i<(tmp.length/2);i+=2)
              {
                if(tmp[(i+1)] != "" && tmp[(i+1)] != null)
                  agt.array[agt.array.length] = new agenten(agt.array.length,tmp[i],tmp[(i+1)]);
              }
              content = "";
              for(var i=0;i<agt.array.length;i++)
              {
                content += "<a href=\"javascript:directory.agenten.show("+i+")\"><img src=\"" + htmlpfad + "/images/layout/plus.gif\" alt=\"+\" border=\"0\" id=\"agt_icon_"+i+"\"/>"+agt.array[i].name+"</a><br />";
                content += "<div id=\"agt_liste_"+i+"\" style=\"display:none;margin-left:15px;\"></div>";
                
              }
            }
            $("agenten_liste").innerHTML = content;
            agt.load = true;
          }});
        }
      }
      this.agenten.show = function(n)
      {
        if($("agt_liste_"+n).style.display != "block")
        {
          $("agt_liste_"+n).style.display = "block";
          $("agt_icon_"+n).src = htmlpfad + "/images/layout/minus.gif";
          $("agt_icon_"+n).alt = "-";
        }
        else
        {
          $("agt_liste_"+n).style.display = "none";
          $("agt_icon_"+n).src = htmlpfad + "/images/layout/plus.gif";
          $("agt_icon_"+n).alt = "+";
        }
        agt.array[n].loadData();
      }
      
      
      /* Favoritenliste ein- und ausblenden und AJAX Request */
      this.favoriten.init = function()
      {
        if($("favoriten_liste").style.display != "block")
        {
          $("favoriten_liste").style.display = "block";
          $("favoriten_icon").src = htmlpfad + "/images/layout/minus.gif";
          $("favoriten_icon").alt = "-";
        }
        else
        {
          $("favoriten_liste").style.display = "none";
          $("favoriten_icon").src = htmlpfad + "/images/layout/plus.gif";
          $("favoriten_icon").alt = "+";
        }
        if($("favoriten_liste").innerHTML)
          return;
        var content = "";
        for(key in fav.array)
        {
          if(isNaN(key))
            continue;
          content += "<a href=\"javascript:directory.favoriten.show("+key+")\"><img src=\"" + htmlpfad + "/images/layout/plus.gif\" alt=\"+\" border=\"0\" id=\"fav_icon_"+key+"\"/>"+fav.array[key][0]+"</a><br />";
          content += "<div id=\"fav_liste_"+key+"\" style=\"display:none;margin-left:15px\"></div>";
        }
        $("favoriten_liste").innerHTML = content;
      }
      this.favoriten.show = function(n)
      {
        if($("fav_liste_"+n).style.display != "block")
        {
          $("fav_liste_"+n).style.display = "block";
          $("fav_icon_"+n).src = htmlpfad + "/images/layout/minus.gif";
          $("fav_icon_"+n).alt = "-";
          if(fav.array[n]["load"] == false)
            fav.loadData(n);
        }
        else
        {
          $("fav_liste_"+n).style.display = "none";
          $("fav_icon_"+n).src = htmlpfad + "/images/layout/plus.gif";
          $("fav_icon_"+n).alt = "+";
        }
      }
      this.favoriten.setData = function(n)
      {
        fav.setData(n);
      }
      this.setName = function(n)
      {
        document.getElementsByName("to")[0].value = n;
        MitgliedExists(document.getElementsByName("to")[0]);
        Hide(4);
      }
      fav.loadData = function(n)
      {
        fav.array[n]["load"] = true;
        new Ajax.Request(htmlpfad + "/ajax/getFavoriten.php",{
          parameters:{n:n},
          onSuccess:function(t){
            if(t.responseText == "xNE")
            {
              $("fav_liste_"+n).innerHTML = "Keine Mitglied vorhanden";
            }
            else
            {
              fav.array[n][1] = t.responseText.split("|");
              directory.favoriten.setData(n);
            }
          }
          });
      }
      fav.setData = function(n)
      {
        var content = "";
        for(key in fav.array[n][1])
        {
          if(isNaN(key))
            continue;
          content += "<a href=\"javascript:directory.setName(\'"+fav.array[n][1][key]+"\')\">"+fav.array[n][1][key]+"</a><br />";
        }
        $("fav_liste_"+n).innerHTML = content;
      }
    }
    var agenten = function(n,id,name)
    {
      this.n = null;
      this.id = null;
      this.name = null;
      this.array = new Array();
      this.load = false;
      this.ret = "";
      
      this.init = function(n,id,name)
      {
        this.n = n;
        this.id = id;
        this.name = name;
      }
      this.loadData = function()
      {
        if(this.load == true)
          return;
        var n = this.n;
        new Ajax.Request(htmlpfad + "/ajax/getAgenten.php",{method:"post",parameters:{n:this.id},onSuccess:function(t){
          if(t.responseText == "xNE")
          {
            $("agt_liste_"+n).innerHTML = "Keine Suchtreffer";
          }
          else
          {
            var tmp = t.responseText.split("|");
            var content = "";
            for(var i=0;i<tmp.length;i++)
            {
              content += "<a href=\"javascript:directory.setName(\'"+tmp[i]+"\')\">"+tmp[i]+"</a><br />";
            }
            $("agt_liste_"+n).innerHTML = content;
          }
        }});
        this.load = true;
      }
      this.init(n,id,name);
    }
    var directory = new adressbuch();

var SexGenderCheck = function(obj1,obj2,obj3,obj4)
{
  this.obj1 = new Object();
  this.obj1.gender = obj1;
  this.obj1.sex = obj2;
  
  this.obj2 = new Object();
  this.obj2.gender = obj3;
  this.obj2.sex = obj4;
  
  this.init = function()
  {
    /*if(navigator.appName != "Microsoft Internet Explorer")
      document.captureEvents(Event.CHANGE);
    this.obj1.gender.onchange = function(){sexcheck.check();};
    
    this.obj1.sex.onchange = function(){sexcheck.check();};
    
    this.obj2.gender.onchange = function(){sexcheck.check();};
    
    this.obj2.sex.onchange = function(){sexcheck.check();};*/
	
	if(navigator.appName == "Microsoft Internet Explorer")
	{
		this.obj1.gender.onchange = function(){sexcheck.check();};
    
		this.obj1.sex.onchange = function(){sexcheck.check();};
    
		this.obj2.gender.onchange = function(){sexcheck.check();};
    
		this.obj2.sex.onchange = function(){sexcheck.check();};
	}
	else
	{
		this.obj1.gender.addEventListener('change',function(){sexcheck.check();},false);
		for(i=0;i<this.obj1.sex.length;i++)
			this.obj1.sex[i].addEventListener('change',function(){sexcheck.check();},false);
		this.obj2.gender.addEventListener('change',function(){sexcheck.check();},false);
		for(i=0;i<this.obj2.sex.length;i++)
			this.obj2.sex[i].addEventListener('change',function(){sexcheck.check();},false);
	}
  }
  
  this.check = function()
  {
	
    if(document.getElementById('partner') && document.getElementById('partner').style.display != "block")
      return;
	
    if(this.obj1.gender.value == 0 || this.obj1.sex.value == 0 || this.obj2.gender.value == 0 || this.obj2.sex.value == 0)
      return;
	
    if(this.obj1.gender.value == this.obj2.gender.value)
    {
      if((this.obj1.sex[0].checked == true || this.obj2.sex[0].checked == true))
      {
        alert("Sie können kein Paar sein!");
        this.unselect();
        return false;
      }
    }
    else
    {
      if((this.obj1.sex[1].checked == true || this.obj2.sex[1].checked == true))
      {
        alert("Sie können kein Paar sein!");
        this.unselect();
        return false;
      }
    }
  }
  
  this.getRadioValue = function(obj)
  {
    for(var i=0;i<obj.length;i++)
    {
      if(obj[i].checked)
        return obj[i].value;
    }
    return "";
  }
  
  this.unselect = function()
  {
    for(var i=0;i<3;i++)
    {
      this.obj1.sex[i].checked = false;
      this.obj2.sex[i].checked = false;
	  if(i<2)
	  {
		  this.obj1.gender[i].checked = false;
	      this.obj2.gender[i].checked = false;
	  }
    }
    this.obj1.gender.selectedIndex = 0;
    this.obj1.sex.selectedIndex = 0;
    this.obj2.gender.selectedIndex = 0;
    this.obj2.sex.selectedIndex = 0;
  }
  
  this.init();
}

var tooltip = function()
{
  var tooltips = new Array();
  var tid = 0;
  this.x = 0;
  this.y = 0;
  this.isShow = false;
  this.array = new Array();
  this.showit = false;
  
  MOUSE = 0;
  TOPLEFT = 1;
  TOPCENTER = 2;
  TOPRIGHT = 3;
  MIDDLELEFT = 4;
  MIDDLERIGHT = 5;
  BOTTOMLEFT = 6;
  BOTTOMCENTER = 7;
  BOTTOMRIGHT = 8;
  
  thisTT = this;
  
  this.init = function()
  {
    if(navigator.appName == "Microsoft Internet Explorer")
		document.onmousemove = thisTT.mousemove;
	else
		document.addEventListener('mousemove', thisTT.mousemove, false);
      //window.captureEvents(Event.MOUSEMOVE);
    
	//
  }
  
  this.show = function(id)
  {
    tid = id;
	this.showit = true;
    if(tooltips[id])
    {
      $("tooltip").innerHTML = tooltips[id];
      $("tooltip_shadow").innerHTML = tooltips[id];
    }
    else
    {
      new Ajax.Request(htmlpfad + "/ajax/getTooltip.php",{method:"post",parameters:{id:id},onSuccess:this.update});
    }
    $("tooltip").style.display = "inline";
    $("tooltip_shadow").style.display = "inline";
  }
  
  this.showText = function(str)
  {
	this.showit = true;
    str = unescape(str);
    tid = 0;
    $("tooltip").innerHTML = str;
    $("tooltip_shadow").innerHTML = str;
    $("tooltip").style.display = "inline";
    $("tooltip_shadow").style.display = "inline";
  }
  
  this.hide = function()
  {
	this.showit = false;
    $("tooltip").style.display = "none";
    $("tooltip_shadow").style.display = "none";
  }
  
  this.mousemove = function(evt)
  {
    if(!$("tooltip"))
      return;
    evt = (evt) ? evt : ((window.event) ? window.event : "");
    var x,y;
    if(document.documentElement)
    {
      x = evt.clientX + document.documentElement.scrollLeft;
      y = evt.clientY + document.documentElement.scrollTop;
    }
    else if(document.body)
    {
      x = evt.clientX + document.body.scrollLeft;
      y = evt.clientY + document.body.scrollTop;
    }
    else
    {
      x = evt.pageX;
      y = evt.pageY;
    }
    this.x = $("tooltip").offsetWidth;
    this.y = $("tooltip").offsetHeight;
    
    var iHeight = 0;
    var iWidth = 0;
    
    if(document.documentElement && document.documentElement.clientHeight)
    {
      iHeight = document.documentElement.clientHeight;
      iWidth = document.documentElement.clientWidth;
    }
    else if(document.body && document.body.clientHeight)
    {
      iHeight = document.body.clientHeight;
      iWidth = document.body.clientWidth;
    }
    else
    {
      iHeight = window.innerHeight;
      iWidth = window.innerWidth;
    }
	
	var scrollTop = 0;
	var scrollLeft = 0;
	//alert(document.body.scrollTop);
	if(document.documentElement && document.documentElement.scrollTop)
	{
		scrollTop = document.documentElement.scrollTop;
		scrollLeft = document.documentElement.scrollLeft;
	}
	else if(document.body && document.body.scrollTop)
	{
		scrollTop = document.body.scrollTop;
		scrollLeft = document.body.scrollLeft;
	}
	else if(window.pageYOffset)
	{
		scrollTop = window.pageYOffset;
		scrollLeft = window.pageXOffset;
	}
    
    if(!tip.array[tid] || tip.array[tid].position == null || tip.array[tid].position == 0)
    {
      if(x > (iWidth / 2))
      {
        $("tooltip").style.left = "";
        $("tooltip").style.right = (iWidth-x+10)+"px";
        $("tooltip_shadow").style.left = "";
        $("tooltip_shadow").style.right = (iWidth-x+8)+"px";
      }
      else
      {
        $("tooltip").style.right = "";
        $("tooltip").style.left = (x+10)+"px";
        $("tooltip_shadow").style.right = "";
        $("tooltip_shadow").style.left = (x+15)+"px";		
      }
      
      if(y > (iHeight / 2))
      {
		var st = (navigator.appVersion.substring(0,1) < 5) ? scrollTop : 0;
        $("tooltip").style.top = "";
        $("tooltip").style.bottom = (iHeight-y+st+10)+"px";
        $("tooltip_shadow").style.top = "";
        $("tooltip_shadow").style.bottom = (iHeight-y+st+8)+"px";
		
		if(iHeight-y-this.y+st < 0)
		{
//			$("tooltip").style.top = scrollTop+"px";
//			$("tooltip").style.bottom = "";
//			$("tooltip_shadow").style.top = (scrollTop+2)+"px";
//			$("tooltip_shadow").style.bottom = "";
			$("tooltip").style.top = '';
			$("tooltip").style.bottom = 8+"px";
			$("tooltip_shadow").style.top = "";
			$("tooltip_shadow").style.bottom = 2+"px";
		}
			//if(iHeight-y-this.y < 0)
			//{
				//alert("iHeight: "+iHeight+"\ny: "+y+"\nthis.y: "+this.y);
			//}
      }
      else
      {
        $("tooltip").style.bottom = "";
        $("tooltip").style.top = (y+10)+"px";
        $("tooltip_shadow").style.bottom = "";
        $("tooltip_shadow").style.top = (y+15)+"px";
		
		if(y+this.y > iHeight+scrollTop)
		{
			$("tooltip").style.bottom = "2px";
			$("tooltip").style.top = "";
			$("tooltip_shadow").style.bottom = "0px";
			$("tooltip_shadow").style.top = "";
		}
      }
    }
    else
    {
      if(tip.array[tid].position >= 1 && tip.array[tid].position <= 3)
      {
        $("tooltip").style.bottom = "";
        $("tooltip").style.top = 10+"px";
        $("tooltip_shadow").style.bottom = "";
        $("tooltip_shadow").style.top = 15+"px";
      }
      else if(tip.array[tid].position >= 6 && tip.array[tid].position <= 8)
      {
        $("tooltip").style.top = "";
        $("tooltip").style.bottom = 10+"px";
        $("tooltip_shadow").style.top = "";
        $("tooltip_shadow").style.bottom = 5+"px";
      }
      else
      {
        $("tooltip").style.bottom = "";
        $("tooltip").style.top = ((iHeight-this.y)/2)+"px";
        $("tooltip_shadow").style.bottom = "";
        $("tooltip_shadow").style.top = ((iHeight-this.y)/2+5)+"px";
      }
      if(tip.array[tid].position == 1 || tip.array[tid].position == 4 || tip.array[tid].position == 6)
      {
        $("tooltip").style.right = "";
        $("tooltip").style.left = 10+"px";
        $("tooltip_shadow").style.right = "";
        $("tooltip_shadow").style.left = 15+"px";
      }
      else if(tip.array[tid].position == 3 || tip.array[tid].position == 5 || tip.array[tid].position == 8)
      {
        $("tooltip").style.left = "";
        $("tooltip").style.right = 10+"px";
        $("tooltip_shadow").style.left = "";
        $("tooltip_shadow").style.right = 5+"px";
      }
      else
      {
        $("tooltip").style.right = "";
        $("tooltip").style.left = ((iWidth-this.x)/2)+"px";
        $("tooltip_shadow").style.right = "";
        $("tooltip_shadow").style.left = ((iWidth-this.x)/2+5)+"px";
      }
    }
    if(tip.array[tid] && tip.array[tid].width)
    {
      $("tooltip").style.width = tip.array[tid].width+"px";
      $("tooltip_shadow").style.width = tip.array[tid].width+"px";
    }
    else
    {
      $("tooltip").style.width = "";
      $("tooltip_shadow").style.width = "";
    }
  }
  this.update = function(t)
  {
    t = t.responseText;
    if(tip.array[tid] && tip.array[tid]["vars"])
    {
      for(var key in tip.array[tid]["vars"])
      {
        var regex = new RegExp("__"+key+"__","g");
        t = t.replace(regex,tip.array[tid]["vars"][key]);
      }
    }
    tooltips[tid] = t;
    $("tooltip").innerHTML = t;
    $("tooltip_shadow").innerHTML = t;	
  }

  this.replace = function()
  {
    if(!$("tooltip"))
    {
      var body = document.getElementsByTagName("body")[0];
      var element1 = document.createElement("div");
      element1.setAttribute("id","tooltip");
      var element2 = document.createElement("div");
      element2.setAttribute("id","tooltip_shadow");
      body.insertBefore(element1,body.firstChild);
      body.insertBefore(element2,body.firstChild);
    }
    var obj = document.getElementsByTagName("*");
    for(var i=0;i<obj.length;i++)
    {
      if(obj[i].title.search(/tooltip:\d/) != -1)
      {
        var erg = obj[i].title.match(/tooltip:(\d*)/);
        obj[i].onmouseover = new Function("tip.show("+erg[1]+")");
        obj[i].onmouseout = tip.hide;
        obj[i].setAttribute("title","");
      }
      else if(obj[i].title.search(/tooltip:.*:\d/) != -1)
      {
        var erg = obj[i].title.match(/tooltip:(.*):(\d*)/);
        eval("var array = "+erg[1]+";");
		tip.array[erg[2]] = new Array();
        tip.array[erg[2]]["vars"] = array;
        obj[i].onmouseover = new Function("tip.show("+erg[2]+")");
        obj[i].onmouseout = tip.hide;
        obj[i].setAttribute("title","");
      }
      else if(obj[i].title.search(/tooltip:.*?/) != -1)
      {
        var erg = obj[i].title.match(/tooltip:(.*)/);
        obj[i].onmouseover = new Function("tip.showText(\""+escape(erg[1])+"\")");
        obj[i].onmouseout = tip.hide;
        obj[i].setAttribute("title","");
      }
    }
  }
  
  this.init()
}
tip = new tooltip();
// In die Onload-Funktion verschoben, in header.php
//window.onload = tip.replace;
function moveup(obj)
{
  tip.hide();
  var element = obj.parentNode.parentNode.parentNode.parentNode.parentNode;
  document.getElementById("bilderliste").removeChild(obj.parentNode.parentNode.parentNode.parentNode.parentNode);
  document.getElementById("bilderliste").insertBefore(element,document.getElementById("bilderliste").firstChild);
  new Ajax.Request(htmlpfad+"/ajax/saveGalerieOrder.php",{method:"post",parameters:Sortable.serialize("profil")+"&"+Sortable.serialize("bilderliste")});
  UpdateList();
}
function movedown(obj)
{
  tip.hide();
  var element = obj.parentNode.parentNode.parentNode.parentNode.parentNode;
  document.getElementById("bilderliste").removeChild(obj.parentNode.parentNode.parentNode.parentNode.parentNode);
  var nodes = document.getElementById("bilderliste").childNodes;
  for(var i=0;i<nodes.length;i++)
  {
    if(nodes[i].tagName.toUpperCase() == "CENTER")
    {
      var node = nodes[i];
      break;
    }
  }
  document.getElementById("bilderliste").insertBefore(element,node);
  new Ajax.Request(htmlpfad+"/ajax/saveGalerieOrder.php",{method:"post",parameters:Sortable.serialize("profil")+"&"+Sortable.serialize("bilderliste")});
  UpdateList();
}
function as_profil_foto(obj)
{
	if(document.getElementById('mess_1'))
		document.getElementById('mess_1').style.display = 'none';
	var top = 0;
	var left = 0;
	obj.checked = false;
	obj = obj.parentNode.parentNode.parentNode.parentNode.parentNode;
	var gobj = obj;
	/*do
	{
		top += parseInt(gobj.offsetTop);
		left += parseInt(gobj.offsetLeft);
		gobj = gobj.parentNode;
	}while(gobj.parentNode && gobj.parentNode.tagName.toUpperCase() != 'HTML');
	if(navigator.appName.indexOf("Internet Explorer") != -1)
	{
		left = parseInt(obj.parentNode.parentNode.offsetLeft);
		top = parseInt(obj.parentNode.parentNode.offsetTop);
	}*/
	/*while(true)
	{
		if(gobj.tagName.toUpperCase() == 'BODY')
			break;
		alert('Top: '+parseInt(gobj.offsetTop)+'; Left: '+parseInt(gobj.offsetLeft));
		top += parseInt(gobj.offsetTop);
		left += parseInt(gobj.offsetLeft);
		gobj = gobj.parentNode;
	}*/
	left = parseInt(obj.parentNode.parentNode.offsetLeft);
	top = parseInt(obj.offsetTop) + parseInt(obj.parentNode.parentNode.offsetTop);
	//alert(left);
	//alert(top);
	left += 4;
	top += 4;
	//var element = obj.parentNode.parentNode.parentNode.parentNode.parentNode.cloneNode(true);
	obj.style.width = '480px';
	obj.style.position = 'absolute';
	obj.style.top = top+'px';
	obj.style.left = left+'px';
	document.getElementsByTagName('body')[0].appendChild(obj);
	
	//document.getElementById("bilderliste").removeChild(obj.parentNode.parentNode.parentNode.parentNode.parentNode);
	var move = new Move(obj);
	move.top = 480;
	move.left = 271;
	move.step = 40;
	move.speed = 50;
	move.onEnd = function(obj){
		obj.style.position = 'relative';
		obj.style.top = 0;
		obj.style.left = 0;
		//document.getElementById('profil').appendChild(obj);
		document.getElementById('profil').insertBefore(obj,document.getElementById('profil').firstChild);
		UpdateList();
		new Ajax.Request(htmlpfad+"/ajax/saveGalerieOrder.php",{method:"post",parameters:serialize("profil")+"&"+serialize("bilderliste")});
	}
	move.Start();
	
}
function as_non_profil_foto(obj)
{
	if(document.getElementById('mess_1'))
		document.getElementById('mess_1').style.display = 'none';
	var top = 0;
	var left = 0;
	obj.checked = false;
	obj = obj.parentNode.parentNode.parentNode.parentNode.parentNode;
	var gobj = obj;
	/*do
	{
		top += parseInt(gobj.offsetTop);
		left += parseInt(gobj.offsetLeft);
		gobj = gobj.offsetParent;
	}while(gobj.offsetParent && gobj.offsetParent.tagName.toUpperCase() != 'HTML')
	if(navigator.appName.indexOf("Internet Explorer") != -1)
	{
		left = parseInt(obj.parentNode.parentNode.offsetLeft);
		top = parseInt(obj.parentNode.parentNode.offsetTop);
	}*/
	left = parseInt(obj.parentNode.parentNode.offsetLeft);
	top = parseInt(obj.offsetTop) + parseInt(obj.parentNode.parentNode.offsetTop);
	left += 4;
	top += 4;
	obj.style.width = '480px';
	obj.style.position = 'absolute';
	obj.style.top = top+'px';
	obj.style.left = left+'px';
	document.getElementsByTagName('body')[0].appendChild(obj);
	var move = new Move(obj);
	move.top = 725;
	if(navigator.appName.indexOf('Microsoft Internet Explorer') != -1)
		move.left = 275;
	else
		move.left = 271;
	move.step = 40;
	move.speed = 50;
	move.onEnd = function(obj){
		obj.style.position = 'relative';
		obj.style.top = 0;
		obj.style.left = 0;
		//document.getElementById('profil').appendChild(obj);
		document.getElementById('bilderliste').insertBefore(obj,document.getElementById('bilderliste').firstChild);
		UpdateList();
		//new Ajax.Request(htmlpfad+"/ajax/saveGalerieOrder.php",{method:"post",parameters:Sortable.serialize("profil")+"&"+Sortable.serialize("bilderliste")});
		new Ajax.Request(htmlpfad+"/ajax/saveGalerieOrder.php",{method:"post",parameters:serialize("profil")+"&"+serialize("bilderliste")});
	}
	move.Start();
}

function serialize(element)
{
	element = $(element);
	var arr = [];
	for(var i=0;i<element.childNodes.length;i++)
	{
		var match = element.childNodes[i].id.match(/\w*_(\d*)/);
		if(match && match[1])
			arr.push(match[1]);
	}
	for(var k in arr)
	{
		arr[k] = element.id+'[]='+arr[k];
	}
	return arr.join('&');
}

function Move(obj)
{
	if(typeof CIterator == 'undefined')
		CIterator = 0;
	else
		CIterator++;
	this.CID = CIterator;
	/*
	
	*/
	this._obj = obj;
	this._cur_top = parseInt(this._obj.style.top);
	this._cur_left = parseInt(this._obj.style.left);
	this._start_top = this._cur_top;
	this._start_left = this._cur_left;
	this._rel = this._cur_left / this._cur_top;
	this.top = 0;
	this.left = 0;
	this.speed = 100;
	this.step = 1;
	this.onStep = function(){};
	this.onEnd = function(){};
}
Move.prototype._move = function()
{
	this.onStep();
	if(this._start_top >= this.top)
		this._cur_top = eval(this._cur_top - this.step);
	else
		this._cur_top = eval(this._cur_top + this.step);

	if(this._start_left >= this.left)
		this._cur_left = eval(this._cur_left - this.step * this._rel);
	else
		this._cur_left = eval(this._cur_left + this.step * this._rel);
	
	//this.debug = new CDebug('Top: '+this._cur_top+'<br />Left: '+this._cur_left);
	
	this._obj.style.top = this._cur_top+'px';
	this._obj.style.left = this._cur_left+'px';
	if(this._start_top <= this.top && this._cur_top >= this.top) // wenn nach unten
	{
		//alert("Start_left: "+this._start_left+"\nLeft: "+this.left+"Cur_Left: "+this._cur_left);
		if(this._start_left <= this.left && this._cur_left >= this.left) // wenn nach links
		{
			window.clearInterval(this.interval);
			this._end();
			this.onEnd(this._obj);
		}
		else if(this._start_left >= this.left && this._cur_left <= this.left) // wenn nach rechts
		{
			window.clearInterval(this.interval);
			this._end();
			this.onEnd(this._obj);
		}
	}
	else if(this._start_top >= this.top && this._cur_top <= this.top) // wenn nach oben
	{
		//alert(this._start_left + ' - ' + this._cur_left + ' - ' + this.left);
		if(this._start_left <= this.left && this._cur_left >= this.left) // wenn nach links
		{
			window.clearInterval(this.interval);
			this._end();
			this.onEnd(this._obj);
		}
		else if(this._start_left >= this.left && this._cur_left <= this.left) // wenn nach rechts
		{
			window.clearInterval(this.interval);
			this._end();
			this.onEnd(this._obj);
		}
	}
}
Move.prototype.Start = function()
{
	this._rel = (this._cur_left - this.left) / (this._cur_top - this.top);
	if(typeof CThis != 'object')
		CThis = new Array();
	CThis[this.CID] = this;
	this.interval = window.setInterval("CThis["+this.CID+"]._move()",this.speed);
}
Move.prototype._end = function()
{
	this._obj.style.top = this.top+'px';
	this._obj.style.left = this.left+'px';
}

function addRow(inst, su)
{
  rows = $("koerper_" + inst).rows.length;
  
  var row = $("koerper_" + inst).insertRow(rows);
  row.setAttribute("bgColor", "#992200");
  var rname = "tab_" + inst + "_z" + rows;
  
  //alert("Name der eingefügten Zeile : " + rname);
  
  row.setAttribute("id", rname);
  
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  var cell3 = row.insertCell(2);
  var cell4 = row.insertCell(3);

  var we1 = $("koerperteil_" + inst).selectedIndex;
  var ind1 = $("koerperteil_" + inst).options[we1].value;
  var text1 = $("koerperteil_" + inst).options[we1].text;
  cell1.innerHTML = text1;
 
  var we2 = $("attribut_" + inst).selectedIndex;
  var ind2 = $("attribut_" + inst).options[we2].value;
  var text2 = $("attribut_" + inst).options[we2].text;
  //cell2.innerHTML = text2;
  
  var we3 = $("bezeichnung_" + inst).selectedIndex;
  var ind3 = $("bezeichnung_" + inst).options[we3].value;
  var text3 = $("bezeichnung_" + inst).options[we3].text;
  //cell3.innerHTML = text3;
  
  new Ajax.Request(htmlpfad + "/ajax/koerper.php",
  {
    method:"post",
    parameters:"ind1=" + ind1 + "&ind2=" + ind2 + "&ind3=" + ind3 + "&su=" + su
  });
  
  new Ajax.Request(htmlpfad + "/ajax/koerpersuffix.php",
  {
  method:"post",
  parameters:{item:rname,bez:ind2,part:ind3},
  onSuccess:function(t){
    var arr = t.responseText.split("|");
    $(arr[0]).childNodes[1].innerHTML = arr[1];
    $(arr[0]).childNodes[2].innerHTML = arr[2];
    
    var ar = arr[0].match(/tab_(\d+)_z\d+/);
    
    var atext = $("k_att_" + ar[1]).innerHTML;
    atext = atext + ", " + arr[1] + " " + arr[2];
    if(atext.substr(0,33) == "noch keine Attribute festgelegt, ")
      atext = atext.substr(33);
    $("k_att_" + inst).innerHTML = atext;
  }
  });

  /*
  Auch dynamisch angelegte Zeilen müssen dynamisch wieder entfernt werden  
  
  cell4.innerHTML = "<a href=\'" + htmlpfad + "/userbereich/kategorien.php?del1=" + ind2 + "&del2=" + ind3 + "\'><img src=\'" + htmlpfad + "/images/suchagenten/delete.png\' title=\'tooltip:5\' border=\'0\'></a>";  
  */
  
  cell4.innerHTML = "<a href=\'javascript:delRow(" + rows + ", " + inst + ", " + ind2 + ", " + ind3 + ", " + su + ")\' style='margin:0'><img src=\'" + htmlpfad + "/images/suchagenten/delete.png\' title=\'tooltip:5\' border=\'0\'></a>";
  
  $("koerperteil_" + inst).selectedIndex = 0;
  $("attribut_" + inst).selectedIndex = 0;
  $("bezeichnung_" + inst).selectedIndex = 0;
  
  var arr = new Array("attribut_" + inst,"bezeichnung_" + inst);
  
  for(var i=0;i<arr.length;i++)
  {
	var nodes = $(arr[i]).childNodes;
	for(var ii=2;ii<nodes.length;ii++)
	{
		if(nodes[ii].tagName == 'OPTION')
			$(arr[i]).removeChild(nodes[ii]);
		//alert(i+" - "+ii+" - "+nodes[ii].tagName);
	}
  }
  
  // Körperteil zur Vorschau hinzufügen
  
  /*var atext = $("k_att_" + inst).innerHTML;
  //atext = atext + ", " + text2 + " " + text3;
  atext = atext + ", " + $(rname).childNodes[1].innerHTML + " " + $(rname).childNodes[2].innerHTML;
  if(atext.substr(0,33) == "noch keine Attribute festgelegt, ")
  atext = atext.substr(33);
  $("k_att_" + inst).innerHTML = atext;*/
  
  
}

// Holt Dropdown-Liste mit Attributen vom Server

function getAtt(inst, su)
{ 
  //alert(inst);

  //var beg = $("koerperteil_" + inst).selectedIndex;
   var beg = $("koerperteil_" + inst).value;
  
  new Ajax.Request(htmlpfad + "/ajax/koerper.php",
  {
    method:"post",
    onSuccess:fillSelect,
    parameters:"beg=" + beg + "&inst=" + inst + "&su=" + su
  });
  
}

var fillSelect = function(t)
{
  var uri = t.responseText;
 
  //alert(uri);
  
  var arr = uri.split("|");
  
  var att = arr[0];    // Selectfeld Attribute 
  var cwert = arr[1];  // Selectfeld Bezeichnungen
  var inst = arr[2];   // Instanznummer
  
  //var beg = $("koerperteil");
  
  $("catt_" + inst).innerHTML = att;
  $("cwert_" + inst).innerHTML = cwert;
  
  tip.replace();
}

function checkForm(inst, su)
{
  var kt = $("koerperteil_" + inst).selectedIndex;
  
  var att = $("attribut_" + inst).selectedIndex; 
  
  var bez = $("bezeichnung_" + inst).selectedIndex; 
  
  if (kt > 0 && att > 0 && bez > 0)
  {
    //alert("alles augefüllt");
    addRow(inst, su);
  }
}

var addPunkt = function(no)
{
  location.href = urlpfad + htmlpfad + "/suche/suche.php?eig="+no+"&fertig=1&show=1";

}

var scrollObject = function(obj)
{
  this.obj = document.getElementById(obj);
  this.parent = this.obj.parentNode;
  this.interval = null;
  this.lastWidth = null;
  
  this.init = function()
  {
    this.obj.style.clip = "rect(0px, " + this.parent.offsetWidth + "px, " + this.parent.offsetHeight + "px, 0px)";
    this.obj.style.whiteSpace = "nowrap";
    this.obj.style.position = "absolute";
    this.obj.style.left = 0;
    this.obj.style.top = 0;
    this.obj.style.overflow = "hidden";
    
    this.parent.style.position = "relative";
    //this.parent.style.height = "100%";
    //this.parent.style.width = "100%";
    
    //window.setTimeout(this.obj.id+".moveleft(-50);"+this.obj.id+".moveleft(50);",200);
	var thisC = this;
	window.setTimeout(function(){thisC.moveleft(-1);thisC.moveleft(1)},500);
  }
  
  this.left = function(int)
  {
	var thisC = this;
	this.interval = window.setInterval(function(){thisC.moveleft(int)},50);
    //this.interval = window.setInterval(this.obj.id+".moveleft("+int+");",50);
  }
  
  this.right = function(int)
  {
    var thisC = this;
	this.interval = window.setInterval(function(){thisC.moveleft(int/-1)},50);
    //this.interval = window.setInterval(this.obj.id+".moveleft(-"+int+");",50);
  }
  
  this.top = function(int)
  {
    var thisC = this;
	this.interval = window.setInterval(function(){thisC.movetop(int)},50);
    //this.interval = window.setInterval(this.obj.id+".movetop("+int+");",50);
  }
  
  this.bottom = function(int)
  {
    var thisC = this;
	this.interval = window.setInterval(function(){thisC.movetop(int/-1)},50);
    //this.interval = window.setInterval(this.obj.id+".movetop(-"+int+");",50);
  }
  
  this.moveleft = function(int)
  {
    int = parseInt(int);
    if(int > 0 && parseInt(this.obj.style.left) >= 0)
    {
      this.clear();
      return;
    }
    else if(int < 0 && this.lastWidth == this.obj.offsetWidth)// parseInt(this.obj.style.left)/-1 >= (this.obj.offsetWidth - this.parent.offsetWidth)
    {
      this.moveleft(int/-1*2);
      this.clear();
      return;
    }
    this.lastWidth = this.obj.offsetWidth;
    this.obj.style.left = (parseInt(this.obj.style.left) + int) + "px";
    this.obj.width = (parseInt(this.obj.style.left)/-1 + this.parent.offsetWidth) + "px"; 
    var top = parseInt(this.obj.style.top) / -1;
    var left = parseInt(this.obj.style.left) / -1;
    var bottom = top + this.parent.offsetHeight;
    var right = left + this.parent.offsetWidth;
    this.obj.style.clip = "rect(" + top + "px, " + right + "px, " + bottom + "px, " + left + "px)";
  }
  
  this.movetop = function(int)
  {
    int = parseInt(int);
    if(int > 0 && parseInt(this.obj.style.top) >= 0)
    {
      this.clear();
      return;
    }
    else if(int < 0 && parseInt(this.obj.style.top)/-1 >= (this.obj.offsetHeight - this.parent.offsetHeight))
    {
      this.clear();
      return;
    }
    this.obj.style.top = parseInt(this.obj.style.top) + int;
    var top = parseInt(this.obj.style.top) / -1;
    var left = parseInt(this.obj.style.left) / -1;
    var bottom = top + this.parent.offsetHeight;
    var right = left + this.parent.offsetWidth;
    this.obj.style.clip = "rect(" + top + "px, " + right + "px, " + bottom + "px, " + left + "px)";
  }
  
  this.clear = function()
  {
    window.clearInterval(this.interval);
  }
  
  this.init();
}

function mouseOver(bild, id, ak)
{
  // 1. = id (name ohne Pfad und endung)
  // 2. = pfad mit Dateiname ohne Endung 

  var arr = bild.split(".");   // 1

  
  var nam = arr[0];
  var typ = arr[1];
    
  if (ak > 0)
  {
    //alert(pfad);
  
    $(id).src = nam + "_a." + typ;
  }
  else
  {
    $(id).src = nam + "." + typ;
  }
}

function set_flashFrame(film) {
  scrollTo(0,0);
  $('flashcontent').style.display = "block";
   var so = new SWFObject(film, "mymovie", "400", "300", "6", "#FFFFFF");
   so.write("flashcontent");

}

function EventHandling(evt)
{
  this.event = (evt) ? evt : window.event;
  
  this.ie = (navigator.appName.indexOf("Explorer") != -1) ? true : false;
}

EventHandling.prototype.getX = function()
{
  if(this.ie)
  {
    if(document.documentElement && document.documentElement.scrollLeft)
      return this.event.clientX + document.documentElement.scrollLeft;
    else if(document.body && document.body.scrollLeft)
      return this.event.clientX + document.body.scrollLeft;
    else
      return this.event.clientX;
  }
  else
  {
    return this.event.pageX;
  }
}

EventHandling.prototype.getY = function()
{
  if(this.ie)
  {
    if(document.documentElement && document.documentElement.scrollTop)
      return this.event.clientY + document.documentElement.scrollTop;
    else if(document.body && document.body.scrollTop)
      return this.event.clientY + document.body.scrollTop;
    else
      return this.event.clientY;
  }
  else
  {
    return this.event.pageY;
  }
}

EventHandling.prototype.getSrcElement = function()
{
  return (this.event.target) ? this.event.target : this.event.srcElement;
}

EventHandling.prototype.getType = function()
{
  return this.event.type;
}

EventHandling.prototype.getCtrlKey = function(key)
{
  switch(key)
  {
    case 'ALT':
      return this.event.altKey;
    case 'STRG':
      return this.event.ctrlKey;
    case 'SHIFT':
      return this.event.shiftKey;
    case 'META':
      return this.event.metaKey;
    default:
      return false;
  }
}

EventHandling.prototype.getTimeStamp = function()
{
  return this.event.timeStamp;
}

EventHandling.prototype.getKeyCode = function()
{
  return (this.event.keyCode) ? this.event.keyCode : this.event.which;
}

var FAQ = new Object();
FAQ.toggle = function(id)
{
  var obj = $('faq'+id);
  if(obj.style.display != 'block')
    obj.style.display = 'block';
  else
    obj.style.display = 'none';
}
FAQ.show = function(id)
{	
  /*new Ajax.Request(htmlpfad + "/ajax/getFAQ.php",{method:'post',parameters:{id:id},onSuccess:function(t){
    alert(t.responseXML.getElementsByTagName("question")[0].firstChild.data);
    alert(t.responseXML.get("question"));
  }});*/
  
  new Ajax.Updater(popup.Content,htmlpfad+"/ajax/getFAQ.php",{method:"post",parameters:{id:id}});
  popup.show();
}

function DIVPopup()
{
  this.wrapper = document.createElement("div");
  this.wrapper.style.width = "300px";
  this.wrapper.style.height = "150px";
  this.wrapper.style.backgroundColor = "#CCCCCC";
  this.wrapper.style.position = "absolute";
  this.wrapper.style.top = "200px";
  this.wrapper.style.left = "350px";
  this.wrapper.style.display = "none";
  this.wrapper.style.zIndex = 64000;
  this.wrapper.style.overflow = "hidden";
  
  this.closeButton = document.createElement("img");
  this.closeButton.src = "/images/windows/delete.png";
  this.closeButton.style.position = "absolute";
  this.closeButton.style.top = "5px";
  this.closeButton.style.right = "5px";
  this.closeButton.onclick = this.hideS;
  
  this.Content = document.createElement("div");
  this.Content.style.position = "absolute";
  this.Content.style.top = "25px";
  this.Content.style.left = "5px";
  this.Content.style.right = "5px";
  this.Content.style.bottom = "5px";
  this.Content.style.padding = "5px";
  this.Content.style.backgroundColor = "#FFFFFF";
  this.Content.style.width = "290px";
  this.Content.style.height = "120px";
  this.Content.style.color = "#000000";
  this.Content.style.overflow = "auto";
  
  this.wrapper.appendChild(this.closeButton)
  this.wrapper.appendChild(this.Content);
  
  document.getElementsByTagName("body")[0].appendChild(this.wrapper);
}

DIVPopup.prototype.show = function()
{
  this.wrapper.style.display = "block";
}

DIVPopup.prototype.hide = function()
{
  this.wrapper.style.display = "none";
}

DIVPopup.prototype.hideS = function(evt)
{
  var event = new EventHandling(evt);
  event.getSrcElement().parentNode.style.display = "none";
}

DIVPopup.prototype.setContent = function(c)
{
  this.Content.innerHTML = c;
}

DIVPopup.prototype.setWidth = function(n)
{
  this.wrapper.style.width = n + "px";
  this.Content.style.width = n - 10 - (parseInt(this.Content.style.left) + parseInt(this.Content.style.right)) + "px";
  this.autoPosition();
}

DIVPopup.prototype.setHeight = function(n)
{
  this.wrapper.style.height = n + "px";
  this.Content.style.height = n - 10 - (parseInt(this.Content.style.top) + parseInt(this.Content.style.bottom)) + "px";
  this.autoPosition();
}

DIVPopup.prototype.autoPosition = function()
{
  if(document.documentElement && document.documentElement.clientHeight)
  {
    iHeight = document.documentElement.clientHeight;
    iWidth = document.documentElement.clientWidth;
  }
  else if(document.body && document.body.clientHeight)
  {
    iHeight = document.body.clientHeight;
    iWidth = document.body.clientWidth;
  }
  else
  {
    iHeight = window.innerHeight;
    iWidth = window.innerWidth;
  }
  
  this.wrapper.style.top = (iHeight - parseInt(this.wrapper.style.height)) / 2 + "px"
  this.wrapper.style.left = (iWidth - parseInt(this.wrapper.style.width)) / 2 + "px"
}


function ErlaubnisAnfordern(user,name)
{
  new Ajax.Request(htmlpfad + "/ajax/ErlaubnisAnfordern.php",{method:"post",parameters:{user:user},onSuccess:function(t)
 {
  var div = new DIVPopup();
  div.setHeight(125);
  div.setWidth(300);
  div.setContent("<div style='font-size:12px;margin:25px 0;text-align:center'>"+name+" wurde darüber informiert, dass Sie Zugriff auf die Bilder erlangen möchten.</div>");
  div.show();
  }}); 	
}

function ClipErlaubnisAnfordern(user, name) {
  new Ajax.Request("/ajax/ClipErlaubnisAnfordern.php", {
      method: 'post',
      parameters: {
          user: user
      },
      onSuccess: function(t) {
          var div = new DIVPopup();
          div.setHeight(125);
          div.setWidth(300);
          div.setContent("<div style='font-size:12px;margin:25px 0; text-align:ceter'>"+name+" wurde darüber informiert, dass Sie Zugriff auf die Clips erlangen möchten.</div>");
          div.show();
      }
  })
}

function neuesFenster_2(adresse,breite,hoehe) 
{
  var breitetotal = screen.width;
  var hoehetotal = screen.height;
  var hoehemitte;
  var breitemitte;
  var myhoehe;
  var mybreite;

  hoehemitte = hoehetotal / 2;
  myhoehe = hoehemitte - (hoehe/2);
  breitemitte = breitetotal / 2 ;
  mybreite = breitemitte - (breite/2) ;
  FensterAuf = this.open(adresse, "CtrlWindow", "toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=yes,width=" + breite + ",height=" + hoehe + ",top=" + myhoehe + ",left=" + mybreite);
  FensterAuf.focus();
  
  return false;
}

var submitform = function(obj)
{
	do
	{
		obj = obj.parentNode;
		if(obj.tagName.toLowerCase() == "body")
			return;
	}
	while(obj.tagName.toLowerCase() != "form");
	
	obj.submit();
}

var getElementsByClassName = function(c)
{
	var objs = document.getElementsByTagName('*');
	var arr = new Array();
	for(var i=0;i<objs.length;i++)
	{
		if(objs[i].className == c)
		{
			arr[arr.length] = objs[i];
			alert(i);
		}
	}
	return arr; 
}

var addTextBox = function(id,obj)
{
	var text = obj.innerHTML;
	if(text.substring(0,6) == "<input")
		return;
	obj.innerHTML = "<input type='text' name='comments["+id+"]' value='"+text+"' style='width:99%' />";
}

var PanicKey = function(ctrl,key,url)
{	
	this.ctrlkey = ctrl;
	this.key = key;
	this.url = url;
}
PanicKey.prototype.action = function(event)
{
	event = new EventHandling(event);
	if(event.getCtrlKey(this.ctrlkey))
	{
		//alert(Keycode2Key(event.getKeyCode())+' - '+this.key);
		if(Keycode2Key(event.getKeyCode()) == this.key)
		{
			location.href = this.url;
		}
	}
}

var kc = new Array();
kc[9] = "TAB";
kc[13] = "ENTER";
kc[27] = "ESC";
kc[35] = "#";
kc[37] = "LINKS";
kc[38] = "HOCH";
kc[39] = "RECHTS";
kc[40] = "RUNTER";
kc[42] = "MAL";
kc[43] = "+";
kc[44] = ",";
kc[45] = "-";
kc[46] = ".";
kc[47] = "GETEILT";
kc[223] = "ß";

var Keycode2Key = function(keycode)
{
	if(keycode >= 97 && keycode <= 122)
		keycode -= 32;
	if(keycode >= 65 && keycode <= 90)
		return String.fromCharCode(keycode);
	else if(keycode >= 48 && keycode <= 57)
		return keycode - 48;
	else if(kc[keycode])
		return kc[keycode];
	return null;
}

var button = function(text)
{
	this.text = text;
	this.link = null;
	if(button.arguments.length > 1)
		this.link = button.arguments[1];
	this.onclick = null;
	this.id = null;
	this.color = null;
	this.style = null;
}

button.prototype.setOnClick = function(a)
{
	this.onclick = a;
}

button.prototype.setId = function(id)
{
	this.id = id;
}

button.prototype.setText = function(t)
{
	this.text = t;
}

button.prototype.setLink = function(l)
{
	this.link = l;
}

button.prototype.setColor = function(c)
{
	this.color = c;
}

button.prototype.setStyle = function(s)
{
	this.style = s;
}

button.prototype.create = function()
{
	var style = new String;
	if(this.style)
		style += this.style+';';
	
	if(this.color)
		style += 'color:'+this.color+';';
		
	var ins = new String;
	if(this.id)
		ins = ' id="'+this.id+'"'
	
	if(this.onclick)
		ins += ' onclick="'+this.onclick+'"';
	
	var id = new String;
	if(this.id)
		id = ' id="'+this.id+'"';
		
	var text = "<span><div>"+this.text+"</div></span>";
	if(this.link)
		return '<a href="'+this.link+'"'+id+' class="button" style="'+style+'"'+ins+'>'+text+'</a>';
	else
		return '<div'+id+' class="button" style="'+style+'"'+ins+'>'+text+'</div>';
}

var PDW_User = new Array();
var PDW_Pic = new Array();
var PDW_LastUser,PDW_LastPic;

var getProfil = function(id,g)
{
	PDW_User[g] = id;
	PDW_LastUser = id;
	new Ajax.Request(htmlpfad+"/ajax/admin/getProfil.php",{method:'post',parameters:{id:id,g:g},onSuccess:function(t){
		var text = t.responseText.split('|');
		var g = (text[0] == 1) ? 'm' : 'w';
		delete text[0];
		$(g).innerHTML = text.join("");
		evalScript(text.join(""));
	}});
	//evalScript('asfsafasfijasifja<h1>asdas</h1><script type="text/javascript">alert("muh");</script>sadsad');
}

var setTime = function(week,from,to)
{
	document.getElementsByName("kw")[0].value = week;
	document.getElementsByName("von")[0].value = from;
	document.getElementsByName("bis")[0].value = to;
}

var setPic = function(obj,g,pic)
{
	if(g)
		PDW_Pic[g] = pic;
	else
		PDW_Pic = pic;
	PDW_LastPic = pic;
	$("pfoto"+g).src = obj.firstChild.src;
	var arr = new Array();
}

var selectProfil = function(g)
{
	var gt = (g==1) ? "m" : "w";
	if(g && document.getElementsByName("user_id")[0])
	{
		document.getElementsByName("user_id")[0].value = PDW_User[g];
		document.getElementsByName("foto_id")[0].value = PDW_Pic[g];
		$("foto").innerHTML = "<img src='"+htmlpfad+"/galerie/getImage.php?id="+PDW_Pic[g]+"&method=mini' />";
	}
	else if(PDW_LastPic)
	{
		if(PDW_LastUser)
			document.getElementsByName("id")[0].value = PDW_LastUser;
		if(PDW_LastPic)
			document.getElementsByName("foto_id")[0].value = PDW_LastPic;
		$("foto").innerHTML = "<img src='"+htmlpfad+"/galerie/getImage.php?id="+PDW_LastPic+"&method=mini' />";
	}
}

var evalScript = function(s)
{
	s = s.replace(/\n/g,'');
	var hits = preg_match_all(s,"<script type=[\"|']text/javascript[\"|'].*?>(.*?)</script>",'g');
	for(var i=0;i<hits.length;i++)
	{
		var t = hits[i][1];
		t = t.replace(/'/g,"\\'");
		window.setTimeout("eval('"+t+"');",1);
	}
}

var var_dump = function(v)
{
	alert(v);
	var show = true;
	var cont="", tabs="", num=0;
	if(var_dump.arguments.length > 1)
	{
		show = false;
		num = var_dump.arguments[1]+1;
		var str = "\t";
		tabs = str.repeat(num);
		num++;
	}
	
	if(typeof v == 'number')
	{
		if(v == parseInt(v))
			cont = tabs+"int("+v+")\n";
		else
			cont = tabs+"float("+v+")\n";
	}
	else if(typeof v == 'string')
	{
		cont = tabs+"string("+v.length+") \""+v+"\"\n";
	}
	else if(typeof v == 'boolean')
	{
		cont = tabs+"bool("+v+")\n";
	}
	else if(typeof v == 'object' && typeof v.length != 'undefined')
	{
		cont = tabs+"array("+v.length+") {\n";
		for(var key in v)
		{
			//if(isNaN(key))
			//	continue;
			cont += tabs+"["+key+"] =>\n";
			cont += var_dump(v[key],num);
		}
		cont += tabs+"}\n";
	}
	else if(typeof v == 'object')
	{
		cont = tabs+"object {\n";
		for(var key in v)
		{
			//if(isNaN(key))
			//	continue;
			cont += tabs+"["+key+"] =>\n";
			cont += "\t"+var_dump(v[key],num);
		}
		cont += tabs+"}\n";
	}
	else if(typeof v == 'function')
	{
		cont = 'function() {\n}';
	}
	
	if(show)
		alert(cont);
	else
		return cont;
}
String.prototype.repeat = function(l){
	return new Array(l+1).join(this);
}

var TabbedArea = function(id,num)
{
	this.id = id;
	this.num = num;
	this.tabs = new Array();
}

TabbedArea.prototype.addTab = function(id,t,cont)
{
	if(typeof this.tabs[id] != 'object')
		this.tabs[id] = new Array();
	this.tabs[id][t] = cont;
}

TabbedArea.prototype.showTab = function(id)
{
	var display,t;
	for(var i=0;i<this.num;i++)
	{
		if(id == i)
		{
			display = 'block';
			t = 'on';
		}
		else
		{
			display = 'none';
			t = 'off';
		}
		$("tabbedarea_"+this.id+"_"+i).style.display = display;
		$("tab_"+this.id+"_"+i).innerHTML = this.tabs[i][t];
	}
}

var Calendar = function()
{
	this.months = new Array('Januar','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember');
	this.Weekdays = new Array('Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag','Sonntag');
	this.WeekdaysShort = new Array('Mo','Di','Mi','Do','Fr','Sa','So');
	this.date = null;
	this.now = new Date();
	this.obj = null;
	this.month = this.now.getMonth()+1;
	this.year = this.now.getFullYear();
	
	this.bgColor = new Object();
	this.bgColor.now = '#7744aa';
	this.bgColor.appointment = '#3333aa';
	this.bgColor.day = '#9999ff';
	this.bgColor.none = '#555555';
	
	this.Color = new Object();
	this.Color.now = '#fff';
	this.Color.appointment = '#fff';
	this.Color.day = '#fff';
	this.Color.none = '#000';
	
	this.appointments = new Array();
	
	this.onclick = function(t){};
}

Calendar.prototype.drawGrid = function()
{
	with(document)
	{
		write("<table border='0' cellspacing='3' cellpadding='1' class='calendar' id='calendar'>");
		write("<tr><td class='arrows' id='navleft'>&lt;&lt;</td><td colspan='3' id='month'>August</td><td colspan='2' id='year'>2008</td><td class='arrows' id='navright'>&gt;&gt;</td></tr>");
		write("<tr>");
		for(var i=0;i<7;i++)
		{
			write("<th>" + this.WeekdaysShort[i] + "</th>");
		}
		for(var i=0;i<6;i++)
		{
			write("<tr>");
			for(var ii=0;ii<7;ii++)
			{
				write("<td></td>");
			}
			write("</tr>");
		}
		write("</tr>");
		write("</table>");
	}
	this.obj = document.getElementById('calendar');
	thisC = this;
	document.getElementById('navleft').onclick = function(){thisC.navLeft()};
	document.getElementById('navright').onclick = function(){thisC.navRight()};
	this.setMonth(this.month,this.year);
}
Calendar.prototype.setMonth = function(month,year)
{
	document.getElementById('month').innerHTML = this.months[month-1];
	document.getElementById('year').innerHTML = year;
	this.month = month;
	this.year = year;
	this.date = new Date();
	this.date.setFullYear(year);
	this.date.setMonth(month);
	this.date.setDate(1);
	this.date = new Date(year-1900,month,1);
	//this.date = new Date(month + " 1, " + year + " 03:00:00");
	//var date = new Date(year,month,1);
	//alert(date.toLocaleString());
	//this.date = new Date(date.getTime());
	//alert(this.date.toLocaleString());
	//alert(Date.prototype.getDay);
	var c = this.obj.firstChild.childNodes;
	var show = false;
	var count = 1;
	var days = this.getDaysOfMonth(this.date.getFullYear(),this.date.getMonth());
	for(var i=0;i<6;i++)
	{
		for(var ii=0;ii<7;ii++)
		{
			if(show == false)
			{
				var day = this.date.getRealDay();
				if(ii == day)
				{
					show = true;
				}
			}
			if(show == true && count > days)
			{
				show = false;
			}
			if(show == true)
			{
				
				var appointment;
				c[i+2].childNodes[ii].style.fontWeight = '';
				c[i+2].childNodes[ii].onmouseover = '';
				c[i+2].childNodes[ii].onmouseout = '';
				thisC = this;
				c[i+2].childNodes[ii].onclick = new Function("thisC.onclick('"+this.year+"-"+this.month+"-"+count+"')");
				if(this.now.getMonth()+1 == this.month && this.now.getDate() == count && this.now.getFullYear() == this.year)
				{
					c[i+2].childNodes[ii].style.backgroundColor = this.bgColor.now;
					c[i+2].childNodes[ii].style.color = this.Color.now;
					c[i+2].childNodes[ii].style.fontWeight = 'bold';
				}
				else if(appointment = this.getAppointment(this.year,this.month,count))
				{
					c[i+2].childNodes[ii].style.backgroundColor = this.bgColor.appointment;
					c[i+2].childNodes[ii].style.color = this.Color.appointment;
					c[i+2].childNodes[ii].onmouseover = new Function("tip.showText(\""+escape(appointment)+"\")");
					c[i+2].childNodes[ii].onmouseout = tip.hide;
				}
				else
				{
					c[i+2].childNodes[ii].style.backgroundColor = this.bgColor.day;
					c[i+2].childNodes[ii].style.color = this.Color.day;
				}
				c[i+2].childNodes[ii].style.cursor = 'pointer';
				c[i+2].childNodes[ii].innerHTML = count;
				count++;
			}
			else
			{
				c[i+2].childNodes[ii].style.cursor = '';;
				c[i+2].childNodes[ii].style.backgroundColor = this.bgColor.none;
				c[i+2].childNodes[ii].innerHTML = '&nbsp;';
				c[i+2].childNodes[ii].onclick = '';
			}
		}
	}
}
Calendar.prototype.getDaysOfMonth = function(year,month)
{
	var days = 31;
	if(month == 4 || month == 6 || month == 9 || month == 11)
		days--;
	if(month == 2)
	{
		days-= 3;
		if(year % 4 == 0)
			days++;
		if(year % 100 == 0)
			days--;
		if(year % 400 == 0)
			days++;
	}
	return days;
}
Calendar.prototype.navLeft = function()
{
	if(this.month == 1)
	{
		this.year--;
		this.month = 12;
	}
	else
		this.month--;
	this.setMonth(this.month,this.year);
}
Calendar.prototype.navRight = function()
{
	if(this.month == 12)
	{
		this.year++;
		this.month = 1;
	}
	else
		this.month++;
	this.setMonth(this.month,this.year);
}
Calendar.prototype.setAppointment = function(date,app)
{
	if(typeof this.appointments[date] != 'object')
		this.appointments[date] = new Array();
	this.appointments[date][this.appointments[date].length] = app;
}
Calendar.prototype.getAppointment = function(year,month,day)
{
	if(!this.appointments[year+"-"+month+"-"+day])
		return false;
	var tooltip;
	var date = new Date(year-1900,month,day);
	var weekday = date.getRealDay();
	// if(weekday == 0)
		// weekday = 7;
	// weekday--;
	tooltip = "<b style='font-size:12px'>" + this.Weekdays[weekday] + " " + day + "." + month + "." + year + "</b><br /><br />";
	for(var i=0;i<this.appointments[year+"-"+month+"-"+day].length;i++)
	{
		tooltip += this.appointments[year+"-"+month+"-"+day][i] + "<br /><br />";
	}
	return tooltip;
}
Date.prototype.getRealDay = function()
{
	var day = this.getDay();
	if(day == 0)
		day = 7;
	day--;
	var cal = new Calendar();
	day += 30 - cal.getDaysOfMonth(this.getFullYear(),this.getMonth());
	if(day<0)
		day += 7;
	if(day > 6)
		day -= 7;
	return day;
}

var saveProfiloptionen = function(obj)
{
	var checked = (obj.checked) ? 1 : 0;
	new Ajax.Request(htmlpfad + "/ajax/saveProfiloptionen.php",{method:'post',parameters:{opt:obj.name,value:checked}});
}

var LimitLength = function(obj,length,obj2)
{
	var len = obj.value.length;
	if(len > length)
	{
		obj.value = obj.value.substring(0,length);
	}
	len = obj.value.length;
	document.getElementById(obj2).innerHTML = "Noch "+(length-len)+" Zeichen übrig";
}

var popup = function(url)
{
	win = open(url,'win1','height=750,width=900,location=no,menubar=no,resizable=no,scrollbars=no,status=no,toolbar=no');
	win.focus();
}

var ProfilBesucherPopup = function(dur,sound)
{
	// Config
	this.height = '100px';
	this.width = '250px';
	this.border = '1px solid black';
	this.bgcolor = '#fff';
	this.bgimage = '';
	this.color = '#000';
	this.fontsize = 12;
	
	// Nichts ändern ab hier
	this.wrapper = null;
	this.text = null;
	this.duration = dur;
	this.sound = sound;
	this.last = new Array();
	thisPBP = this;
	this.check();
	window.setInterval("thisPBP.check()",(this.duration*1000));
	/*if(this.sound)
		this.objSound = new CSound('/sounds/ringin.mp3');*/
	this.createElement();
}

ProfilBesucherPopup.prototype.createElement = function()
{
	var h = screen.availHeight;
	var b = screen.availWidth;
	var x = (h - parseInt(this.height))/2-100;
	var y = (b - parseInt(this.width))/2;
	

  
	var wrapper = document.createElement('div');
	wrapper.style.position = 'absolute';
	wrapper.style.height = this.height;
	wrapper.style.width = this.width;
	wrapper.style.top = x+'px';
	wrapper.style.left = y+'px';
	wrapper.style.border = this.border;
	wrapper.style.backgroundColor = this.bgcolor;
	wrapper.style.backgroundImage = this.bgimage;
	wrapper.style.color = this.color;
	wrapper.style.textAlign = 'center';
	wrapper.style.zIndex = 9999;
	wrapper.style.display = 'none';
	wrapper.style.fontSize = this.fontsize+'px';

	var text = document.createElement('div');
	text.style.position = 'absolute';
	text.style.top = '10px';
	text.style.left = '0px';
	text.style.bottom = '20px';
	text.style.right = '0px';
	text.style.width = this.width;
  
  var t1 = parseInt(this.height);
  var t2 = text.style.height;
  
  if (text.style.height > 0)
  {
    t2 = parseInt(text.style.height);
  }

	text.style.top = (t1 - t2) / 2 * 0.5 + 'px';
	text.style.textAlign = 'center';

	this.text = text;
	wrapper.appendChild(text);
	
	var button = document.createElement('input');
	button.setAttribute('type','button');
	button.setAttribute('value','Schließen');
	button.style.width = '80px';
	button.style.position = 'absolute';
	button.style.left = (parseInt(this.width) - parseInt(button.style.width)) / 2 + 'px';
	button.style.bottom = '1px';

	button.onclick = function(){ thisPBP.hide();};
	
	wrapper.appendChild(button);
	
	this.wrapper = wrapper;
	document.getElementsByTagName('body')[0].appendChild(wrapper);
	
}

ProfilBesucherPopup.prototype.check = function()
{
	new Ajax.Request(htmlpfad+"/ajax/getlastprofilvisitor.php",{method:"post",onSuccess:function(t){
		thisPBP.checkResponse(t);
	}});
}

ProfilBesucherPopup.prototype.checkResponse = function(t)
{
	if(!t.responseXML)
		return;
	var xml = t.responseXML;

	var users = xml.getElementsByTagName('user');
	if(!users.length)
		return;
	var UserArray = new Array();
	
	for(var i=0;i<users.length;i++)
	{
		//var id = root.childNodes[i].getElementsByTagName('UserID')[0].firstChild.nodeValue;
		var id = users[i].getElementsByTagName('MitgliedID')[0].firstChild.nodeValue;
		var name = users[i].getElementsByTagName('Nickname')[0].firstChild.nodeValue;
		var time = users[i].getElementsByTagName('Time')[0].firstChild.nodeValue;
		UserArray[UserArray.length] = new Array(id,name,time);
		//alert(id);
	}
	this.popup(UserArray);
}


ProfilBesucherPopup.prototype.popup = function(array)
{
	var len = array.length
	var height = len * 20;
	if(height > 100)
		height = 100;
	height += 80;
	
	this.wrapper.style.height = height + 'px';
	
	var text = "";
	for(var k=0;k<array.length;k++)
	{
		text += "<div style='border:1px solid red;width:"+(parseInt(this.width)-25)+"px;margin:0 auto;padding:5px'><a href='/userbereich/profil.php?number="+array[k][0]+"' style='color:"+this.color+"'>"+array[k][1]+"</a> hat soeben Ihr Profil besucht.</div><br />";
	}
	this.setText(text);
	//this.setText(name+' hat so ebend Ihr Profil Besucht');
	this.show();
}

ProfilBesucherPopup.prototype.setText = function(text)
{
	this.text.innerHTML = text;
}

ProfilBesucherPopup.prototype.show = function()
{
	this.playSound();
	this.wrapper.style.display = 'block';
}

ProfilBesucherPopup.prototype.hide = function()
{
	this.wrapper.style.display = 'none';
}

ProfilBesucherPopup.prototype.playSound = function()
{
	if(!this.sound)
		return;
	//this.objSound.play();
}

//new ProfilBesucherPopup(10,false);

var CSound = function(file)
{
	if(typeof CIterator == 'undefined')
		CIterator = 0;
	else
		CIterator++;
	this.CID = CIterator;
	/*
	if(typeof CThis != 'object')
		CThis = new Array();
	CThis[this.CID] = this;
	*/
			
	this.file = file;
	if(CSound.arguments.length > 1)
		this.id = CSound.arguments[1];
	
	IE = !!(navigator.plugins && document.all);
	NN = !!(navigator.plugins && navigator.plugins["LiveAudio"]);
	var quicktime = false;
	if(!IE && !NN)
	{
		for(var k in navigator.plugins)
		{
			if(navigator.plugins[k]['name'].indexOf('QuickTime'))
			{
				quicktime = true;
				break;
			}
		}
	}
	FF = !!(navigator.plugins && quicktime);
	//alert(IE +' '+ NN +' '+ FF);
	if(IE || NN || FF)
		this._insertElement();
}

CSound.prototype._insertElement = function()
{	
	this.element = document.createElement('embed');
	this.element.src = this.file;
	if(this.id)
		this.element.id = this.id;
	this.element.setAttribute('autostart','false');
	this.element.setAttribute('MASTERSOUND','MASTERSOUND');
	this.element.setAttribute('type','audio/mpeg');
	this.element.style.position = 'absolute';
	this.element.style.height = '0px';
	this.element.style.width = '0px';
	this.element.style.border = '1px solid red';
	this.element.style.opacity = '0';
	this.element.style.KhtmlOpacity = '0';
	this.element.style.MozOpacity = '0';
	this.element.style.filter = 'alpha(opacity=0)';
	//this.element.setAttribute('hidden','true');

	document.getElementsByTagName('body')[0].appendChild(this.element);

}

CSound.prototype.play = function()
{
	if(IE)
		this.element.play();
	else if(NN)
		this.element.play(true);
	else if(FF)
		this.element.Play();
	this.element.Play();
}

CSound.prototype.pause = function()
{
	if(IE || NN || FF)
		this.element.pause();
}

CSound.prototype.stop = function()
{
	if(IE || NN)
		this.element.stop();
	else if(FF)
		this.element.Stop();
}

var CDebug = function(text)
{
	this.text = text;
	this._createBox();	
}

CDebug.prototype._createBox = function()
{
	if(document.getElementById('debug_box'))
	{
		this.element = document.getElementById('debug_box');
		this.element.style.display = 'block';
		this.element.firstChild.innerHTML = this.text;
		this.show();
	}
	this.element = document.createElement('div');
	this.element.id = 'debug_box';
	this.element.style.border = '1px solid red';
	this.element.style.backgroundColor = '#fff';
	this.element.style.padding = '5px';
	this.element.style.paddingTop = '15px';
	this.element.style.position = 'fixed';
	this.element.style.left = '20px';
	this.element.style.bottom = '15px';
	
	var ele = document.createElement('div');
	ele.style.color = '#000';
	ele.style.fontSize = '12px';
	ele.style.whiteSpace = 'pre';
	ele.innerHTML = this.text;
	
	this.element.appendChild(ele);
	
	var cross = document.createElement('a');
	cross.style.position = 'absolute';
	cross.style.top = '2px';
	cross.style.right = '2px';
	cross.style.fontSize = '14px';
	cross.style.fontWeight = 'bold';
	cross.style.color = '#fff';
	cross.style.backgroundColor = '#f00';
	cross.innerHTML = 'X';
	thisD = this;
	cross.onclick = function() { thisD.hide(); };
	
	this.element.appendChild(cross);
	
	document.getElementsByTagName('body')[0].appendChild(this.element);
}

CDebug.prototype.show = function()
{
	this.element.style.display = 'block';
}

CDebug.prototype.hide = function()
{
	this.element.style.display = 'none';
}

var pbp_onclick = function(obj)
{
	if(obj.checked == true)
	{
		var col = '#fff';
		var dis = false;
	}
	else
	{
		var col = '#aaa';
		var dis = true;
	}
	document.getElementById('mit_sound').style.color = col;
	document.getElementsByName('profilbesuchpopup_sound')[0].disabled = dis;
}

parse_GET = function()
{
	_GET = {};
	location.search.substring(1,location.search.length).split('&').each(function(value,index){
		var _2 = value.split('=');
		_GET[_2[0]] = _2[1];
	});
}

var ChatInvite = function(dur)
{
	// Config
	this.height = '100px';
	this.width = '250px';
	this.border = '1px solid black';
	this.bgcolor = '#fff';
	this.bgimage = '';
	this.color = '#000';
	this.fontsize = 12;
	
	// Nichts ändern ab hier
	this.wrapper = null;
	this.text = null;
	this.duration = dur;
	this.last = new Array();
	thisCI = this;
	this.check();
	window.setInterval("thisCI.check()",(this.duration*1000));
	this.createElement();
}

ChatInvite.prototype.createElement = function()
{
	var h = screen.availHeight;
	var b = screen.availWidth;
	var x = (h - parseInt(this.height))/2-100;
	var y = (b - parseInt(this.width))/2;
	

  
	var wrapper = document.createElement('div');
	wrapper.style.position = 'fixed';
	wrapper.style.height = this.height;
	wrapper.style.width = this.width;
	wrapper.style.top = x+'px';
	wrapper.style.left = y+'px';
	wrapper.style.border = this.border;
	wrapper.style.backgroundColor = this.bgcolor;
	wrapper.style.backgroundImage = this.bgimage;
	wrapper.style.color = this.color;
	wrapper.style.textAlign = 'center';
	wrapper.style.zIndex = 9999;
	wrapper.style.display = 'none';
	wrapper.style.fontSize = this.fontsize+'px';

	var text = document.createElement('div');
	text.style.position = 'absolute';
	text.style.top = '10px';
	text.style.left = '5px';
	text.style.bottom = '20px';
	text.style.right = '5px';
	text.style.width = this.width;
  
  var t1 = parseInt(this.height);
  var t2 = text.style.height;
  
  if (text.style.height > 0)
  {
    t2 = parseInt(text.style.height);
  }

	text.style.top = (t1 - t2) / 2 * 0.8 + 'px';
	text.style.textAlign = 'center';

	this.text = text;
	wrapper.appendChild(text);
	
	var button = document.createElement('input');
	button.setAttribute('type','button');
	button.setAttribute('value','Schließen');
	button.style.width = '80px';
	button.style.position = 'absolute';
	button.style.left = (parseInt(this.width) - parseInt(button.style.width)) / 2 + 'px';
	button.style.bottom = '1px';
	button.onclick = function(){ thisCI.hide();};
	
	wrapper.appendChild(button);
	
	this.wrapper = wrapper;
	document.getElementsByTagName('body')[0].appendChild(wrapper);
}

ChatInvite.prototype.check = function()
{
	new Ajax.Request(htmlpfad+"/ajax/getChatInvites.php",{method:"post",onSuccess:function(t){
		//var arr = t.responseText.split("|");
		thisCI.checkResponse(t);
	}});
}

ChatInvite.prototype.checkResponse = function(t)
{
	
	if(!t.responseXML)
		return;
	var xml = t.responseXML;

	var users = xml.getElementsByTagName('user');
	if(!users.length)
		return;
	var UserArray = new Array();
	
	for(var i=0;i<users.length;i++)
	{
		//var id = root.childNodes[i].getElementsByTagName('UserID')[0].firstChild.nodeValue;
		
		var id = users[i].getElementsByTagName('MitgliedID')[0].firstChild.nodeValue;
		var name = users[i].getElementsByTagName('Nickname')[0].firstChild.nodeValue;
		var csid = users[i].getElementsByTagName('ChatSessionId')[0].firstChild.nodeValue;
		UserArray[UserArray.length] = new Array(id,name,csid);
		//alert(id);
	}
	
	for(var i=0;i<UserArray.length;i++)
	{
		if($('popup_'+UserArray[i][2]))
			continue;
		var msg = new CMessage(UserArray[i][1]+" hat Sie zu einem Chat eingeladen.<br />Wollen Sie den Chat betreten?<br /><br /><input type='button' value='Ja' style='width:80px' onclick='openChatPopup("+UserArray[i][2]+")' /> <input type='button' value='Nein' style='width:80px' onclick='closeChatQuestion("+UserArray[i][2]+")' />");
		msg.setTitle('Chat Einladung');
		msg.setID('popup_'+UserArray[i][2]);
		msg.setWidth(350);
		msg.setIcon(false);
		msg.closeAfter(120);
		msg.asPopup();
		/*if(confirm(UserArray[i][1]+" hat Sie zu einem Chat eingeladen.\nWollen Sie den Chat betreten?"))
		{
			var win = window.open('/chat/chat.php?chatid='+UserArray[i][2],'_blank','height=400,width=600,location=no,menubar=no,resizable=no,status=no,toolbar=no');
			win.focus();
		}
		else
		{
			//absage erteilen
		}*/
	}
	//this.popup(UserArray);
}

ChatInvite.prototype.setText = function(text)
{
	this.text.innerHTML = text;
}

ChatInvite.prototype.show = function()
{
	this.wrapper.style.display = 'block';
}

ChatInvite.prototype.hide = function()
{
	this.wrapper.style.display = 'none';
}

openChatPopup = function(id)
{
	if($('popup_'+id))
		$('popup_'+id).style.display = 'none';
	new Ajax.Request("/chat/ajax/joinSession.php",{method:'get',parameters:{chatid:id}});
	window.open("/chat/chat.php?chatid="+id,"_blank","height=470,width=630,location=no,menubar=no,resizable=no,status=no,toolbar=no").focus()
}

openChat = function(id)
{
	window.open("/chat/chat.php?user="+id,"_blank","height=470,width=630,location=no,menubar=no,resizable=no,status=no,toolbar=no").focus()
}

closeChatQuestion = function(id)
{
	$('popup_'+id).style.display = 'none';
	
	new Ajax.Request("/chat/ajax/abortInvite.php",{method:'get',parameters:{chatid:id}});
}

var CMessage = function(msg)
{
	if(typeof CIterator == 'undefined')
		CIterator = 0;
	else
		CIterator++;
	this.CID = CIterator;
	if(typeof CThis != 'object')
		CThis = new Array();
	CThis[this.CID] = this;
	
	this.wrapper = null;
	this.width = 200;
	this.border = '1px solid #f00';
	this.background = '#fff';
	this.corner = 10;
	this.title = '';
	this.msg = msg;
	this.icon = true;
	this.id = 'mess_x'+this.CID;
	this.closeafter = 0;
}
CMessage.prototype = {
	setMessage: function(msg){
		this.msg = msg;
	},
	setTitle: function(title){
		this.title = title;
	},
	setWidth: function(width){
		this.width = width;
	},
	setIcon: function(b){
		this.icon = b;
	},
	setID: function(id){
		this.id = id;
	},
	createElement: function(){
		this.wrapper = document.createElement('div');
		this.wrapper.id = this.id;
		this.wrapper.style.zIndex = 10000;
		this.wrapper.appendChild(document.createElement('br'));
		var center = document.createElement('center');
		var div = document.createElement('div');
		div.style.width = this.width+'px';
		div.style.border = this.border;
		div.style.backgroundColor = this.background;
		div.style.MozBorderRadius = this.corner+'px';
		div.style.padding = '10px';
		if(this.icon)
		{
			var icon = document.createElement('img');
			icon.src = '/images/layout/delete.png';
			icon.style.cursor = 'pointer';
			icon.style.cssFloat = 'right';
			icon.style.styleFloat = 'right';
			icon.addEventListener('click',new Function("CThis["+this.CID+"].wrapper.style.display='none'"), false);
			div.appendChild(icon);
		}
		if(this.title != '')
		{
			var titleC = document.createElement('center');
			var title = document.createElement('b');
			title.className = 'msg_titel';
			title.innerHTML = this.title;
			titleC.appendChild(title);
			div.appendChild(titleC);
			div.appendChild(document.createElement('br'));
		}
		var msg = document.createElement('span');
		msg.className = 'msg_text';
		msg.innerHTML = this.msg;
		div.appendChild(msg);
		center.appendChild(div);
		this.wrapper.appendChild(center);
		return this.wrapper;
	},
	getElement:function(){
		return this.createElement();
	},
	asPopup:function(){
		this.createElement();
		this.wrapper.style.position = 'fixed';
		this.wrapper.style.top = '250px';
		this.wrapper.style.left = '400px';
		if(this.closeafter > 0)
		{
			window.setTimeout("CThis["+this.CID+"].wrapper.style.display='none'",this.closeafter*1000);
		}
		document.getElementsByTagName('body')[0].appendChild(this.wrapper);
	},
	closeAfter:function(secs){
		this.closeafter = secs;
	}
}

String.prototype.toRegExpString = function()
{
	return this.replace(/([\^\$\.\*\+\?\=\!\:\|\\\/\(\)\[\]\{\}])/g,"\\$1");
}

invertSelection = function(name)
{
    $A(document.getElementsByName(name)).each(function(element){
        element.checked = !element.checked;
    });
}
sendMassmail = function()
{
    var uri = [];
    $A(document.getElementsByName('massmail[]')).each(function(element){
        if(element.checked)
            uri.push('mm[]='+element.value);
    });
    if(uri.length > 0)
        document.location.href = 'massmail.php?'+uri.join('&');
    else
        alert('Keine User ausgewählt');
}
getUserprofil = function(field,username)
{
    field = $(field);

    new Ajax.Updater(field,"/ajax/getProfil.php",{
        method:"post",
        parameters:{
            name:username
        }
    });
}
setReaded = function()
{
    var uri = [];
    $A(document.getElementsByName('readed[]')).each(function(element){
        if(element.checked)
            uri.push('readed[]='+element.value);
    });
    parse_GET()
    if(uri.length > 0)
        document.location.href = 'user.php?us='+_GET['us']+'&'+uri.join('&');
    else
        alert('keine Nachrichten ausgewählt');
}

CPopup = Class.create({
    initialize: function(){
        this.loaded = false;
        this.options = {
            bgColor: '#fff',
            bgOpacity: '0.5',
            bgZIndex: 1000,
            clickonbackground: false,
            autoload: false,
            contentHeight: 'auto',
            contentWidth: 'auto',
            contentBgColor: '#fff',
            contentBorder: '1px solid black',
            contentZIndex: 1001,
            overflow: 'hidden',
            closeButton: true,
            shadow: true,
            speed: 0.2,
            position: (parseInt(navigator.appVersion) < 5) ? 'absolute' : 'fixed',
            posX: 'auto',
            posY: 'auto',
            closeable: true
        }
        Object.extend(this.options, arguments[0] || {});
        this.elements = {
            bg: null,
            window: null,
            wrapper: null,
            shadow: null
        };
        if(document.loaded)
            this._insertElements();
        else
            Event.observe(window,'load',this._insertElements.bind(this));
    },
    _insertElements: function(){
        
        this.elements.bg = new Element('div', {});
        this.elements.bg.setStyle({
            backgroundColor: this.options.bgColor,
            position: this.options.position,
            top: '0px',
            left: '0px',
            height: '100%',
            width: '100%',
            opacity: this.options.bgOpacity,
            zIndex: this.options.bgZIndex
        });
        
        if(!this.options.autoload)
            this.elements.bg.hide();

        if(this.options.clickonbackground)
            Event.observe(this.elements.bg,'click',this.hide.bind(this));

//        document.getElementsByTagName('body')[0].insert({
//            bottom: this.elements.bg
//        });
            document.getElementsByTagName('body')[0].appendChild(this.elements.bg);

        this.elements.window = new Element('div', {});
        this.elements.window.setStyle({
            backgroundColor: this.options.contentBgColor,
            position: this.options.position,
            top: Math.round((parseInt(document.viewport.getHeight())-parseInt(this.options.contentHeight))/2)+'px',
            left: Math.round((parseInt(document.viewport.getWidth())-parseInt(this.options.contentWidth))/2)+'px',
            border: this.options.contentBorder,
            zIndex: this.options.contentZIndex,
            height: this.options.contentHeight,
            width: this.options.contentWidth,
            overflow: this.options.overflow
        });

        this.elements.window.hide();

        this.elements.wrapper = new Element('div');

        this.elements.window.insert({
            top: this.elements.wrapper
        })

        if(this.options.closeButton)
        {
            this.elements.closeButton = new Element('img',{
                src: '/images/suchagenten/delete.png',
                alt: 'Close'
            }),
            this.elements.closeButton.setStyle({
                position: 'absolute',
                top: '3px',
                right: '2px',
                cursor: 'pointer'
            });

            Event.observe(this.elements.closeButton,'click',this.hide.bind(this));
            this.elements.window.insert({
                bottom: this.elements.closeButton
            })
        }

//        document.getElementsByTagName('body')[0].insert({
//            bottom: this.elements.window
//        });
document.getElementsByTagName('body')[0].appendChild(this.elements.window);

        if(this.options.shadow)
        {
            this.elements.shadow = new Element('div', {});
            this.elements.shadow.setStyle({
                backgroundColor: '#000',
                position: this.options.position,
                top: Math.round((parseInt(document.viewport.getHeight())-parseInt(this.options.contentHeight))/2)+8+'px',
                left: Math.round((parseInt(document.viewport.getWidth())-parseInt(this.options.contentWidth))/2)+8+'px',
                zIndex: (this.options.contentZIndex-1),
                height: this.options.contentHeight,
                width: this.options.contentWidth,
                opacity: 0.5
            });

            this.elements.shadow.hide();

//            document.getElementsByTagName('body')[0].insert({
//                bottom: this.elements.shadow
//            });
        document.getElementsByTagName('body')[0].appendChild(this.elements.shadow);
        }

        if(this.options.autoload)
        {
            Effect.Grow(this.elements.window,{duration:this.options.speed});
            if(this.options.shadow)
                Effect.Grow(this.elements.shadow,{duration:this.options.speed});
        }
        Event.observe(window,'resize',this._position.bind(this));
        this.loaded = true;
    },
    hide: function(){
        if(this.options.closeable != true)
            return;
        this.elements.bg.hide();
        this.elements.window.hide();
        if(this.options.shadow)
            this.elements.shadow.hide();
    },
    show: function(){
        this.elements.bg.show();
        Effect.Grow(this.elements.window,{duration:this.options.speed});
        if(this.options.shadow)
            Effect.Grow(this.elements.shadow,{duration:this.options.speed});
    },
    setContent: function(content){
        if(!document.loaded)
        {
            Event.observe(window,'load',this.setContent.bind(this,content));
            return;
        }
        if(!this.loaded)
        {
            setTimeout(this.setContent.bind(this,content),100);
            return;
        }
        if(content && content.toElement)
            content = content.toElement();
        else if(!Object.isElement(content))
            content = Object.toHTML(content);
        this.elements.wrapper.innerHTML = '';
        this.elements.wrapper.insert({
            bottom: content
        });
        //this.addCloseButton();
        this._position();
    },
    _position: function(){
        this.elements.shadow.setStyle({
            height: this.elements.window.getHeight()+'px'
        });
        this.elements.shadow.setStyle({
            width: this.elements.window.getWidth()+'px'
        });
        this.elements.window.setStyle({
            top: Math.round((parseInt(document.viewport.getHeight())-parseInt(this.elements.window.getHeight()))/2)+'px',
            left: Math.round((parseInt(document.viewport.getWidth())-parseInt(this.elements.window.getWidth()))/2)+'px'
        });
        this.elements.shadow.setStyle({
            top: Math.round((parseInt(document.viewport.getHeight())-parseInt(this.elements.window.getHeight()))/2)+8+'px',
            left: Math.round((parseInt(document.viewport.getWidth())-parseInt(this.elements.window.getWidth()))/2)+8+'px'
        });
    }/*,
    addCloseButton: function(){
        if(!Object.isElement(this.elements.closeButton))
            return;
        this.elements.window.insert({
            top: this.elements.closeButton
        });
    }*/
});

    ScrollArea = Class.create({
        initialize: function(area,content){
            this.options = {
                moveUp: null,
                moveDown: null,
                moveLeft: null,
                moveRight: null,
                eventType: 'mouseover',
                overScrollX: 0,
                overScrollY: 0,
                SliderY: null,
                SliderX: null
            }

            Object.extend(this.options, arguments[2] || {});

            this.area = $(area);
            this.content = $(content);

            this.pos = {
                x: 0,
                y: 0
            };

            var position = (this.area.getStyle('position') == 'static') ? 'relative' : this.area.getStyle('position');

            this.area.setStyle({
                position: position,
                overflow: 'hidden'
            });

            this.periodicalExecuter = {};

            if(!document.loaded)
                Element.observe(window,'load',this._startUp.bind(this));
        },
        _startUp: function(){
            if(this.options.SliderY) {
                if(this.options.SliderY.size() < 2) {
                    this.options.SliderY[1] = this.options.SliderY[0].insert({
                        bottom: new Element('div').setStyle({backgroundColor:'black'})
                    });
                }
                if(this.options.SliderY[0].getStyle('position') == 'static')
                    this.options.SliderY[0].setStyle({
                        position: 'relative'
                    });
                width = this.options.SliderY[0].getWidth() * (this.area.getWidth() / (this.content.getWidth()+2*this.options.overScrollY));
                this.options.SliderY[1].setStyle({
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    width: width+'px'
                });
                this.options.SliderY[1].observe('mousedown',this.startSlidingY.bindAsEventListener(this));
                //this.options.SliderY[1].observe('mouseup',this.stopSlidingY.bind(this));
                Element.observe(window,'mouseup',this.stopSlidingY.bind(this));
                //this.options.SliderY[1].observe('mouseout',this.stopSlidingY.bind(this));
            }
            if(this.options.SliderX) {
                if(this.options.SliderX.size() < 2) {
                    this.options.SliderX[1] = this.options.SliderX[0].insert({
                        bottom: new Element('div').setStyle({backgroundColor:'black'})
                    });
                }
                if(this.options.SliderX[0].getStyle('position') == 'static')
                    this.options.SliderX[0].setStyle({
                        position: 'relative'
                    });
                height = this.options.SliderX[0].getHeight() * (this.area.getHeight() / (this.content.getHeight()+2*this.options.overScrollX));
                this.options.SliderX[1].setStyle({
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    height: height+'px'
                });

                this.options.SliderX[1].observe('mousedown',this.startSlidingX.bindAsEventListener(this));
                //this.options.SliderY[1].observe('mouseup',this.stopSlidingY.bind(this));
                Element.observe(window,'mouseup',this.stopSlidingX.bind(this));
                //this.options.SliderY[1].observe('mouseout',this.stopSlidingY.bind(this));
            }

            this.content.absolutize();

            this.pos.x = parseInt(this.content.getStyle('top'));
            this.pos.y = parseInt(this.content.getStyle('left'));


            var startEvent = (this.options.eventType == 'mouseover') ? 'mouseover' : 'mousedown';
            var endEvent = (this.options.eventType == 'mouseover') ? 'mouseout' : 'mouseup';

            if(Object.isElement(this.options.moveUp)){
                this.options.moveUp.observe(startEvent,this.startMovingX.bind(this,'-3'));
                this.options.moveUp.observe(endEvent,this.stopMovingX.bind(this));
            }
            if(Object.isElement(this.options.moveDown)){
                this.options.moveDown.observe(startEvent,this.startMovingX.bind(this,'3'));
                this.options.moveDown.observe(endEvent,this.stopMovingX.bind(this));
            }
            if(Object.isElement(this.options.moveLeft)){
                this.options.moveLeft.observe(startEvent,this.startMovingY.bind(this,'-10'));
                this.options.moveLeft.observe(endEvent,this.stopMovingY.bind(this));
            }
            if(Object.isElement(this.options.moveRight)){
                this.options.moveRight.observe(startEvent,this.startMovingY.bind(this,'10'));
                this.options.moveRight.observe(endEvent,this.stopMovingY.bind(this));
            }

            /*Element.observe(window,'DOMMouseScroll',function(x){alert(x.scroll())});
            //Element.observe(window,'mousewheel',function(x){alert(x.scroll())});
            document.onmousewheel = function(x){alert('test')};*/
            this.area.observe('DOMMouseScroll',this.scroll.bindAsEventListener(this));
            this.area.observe('mousewheel',this.scroll.bindAsEventListener(this));
        },
        moveToX: function(x){
            if(!document.loaded)
                Element.observe(window,'load',this.moveToX.bind(this,x));
            /*if(this.area.getHeight() < this.content.getHeight() && eval(x+'+'+this.content.getHeight()) < this.area.getHeight())
                x = 0 - this.content.getHeight() + this.area.getHeight();
            else if(this.area.getHeight() >= this.content.getHeight() && x < 0 - this.options.overScrollX)
                x = 0 - this.options.overScrollX;
            else if(eval(x+'-'+this.options.overScrollX) > this.area.getHeight() - this.content.getHeight())
                x = this.area.getHeight() - this.content.getHeight() + this.options.overScrollX;*/
            if(this.area.getHeight() <= this.content.getHeight() && x > 0 + this.options.overScrollX)
                x = 0 + this.options.overScrollX;
            else if(this.area.getHeight() <= this.content.getHeight() && x < this.area.getHeight() - this.content.getHeight() - this.options.overScrollX)
                x = this.area.getHeight() - this.content.getHeight() - this.options.overScrollX;
            else if(this.area.getHeight() > this.content.getHeight() && x < 0 + this.options.overScrollX)
                x = 0 + this.options.overScrollX;
            else if(this.area.getHeight() > this.content.getHeight() && x > this.area.getHeight() - this.content.getHeight() + this.options.overScrollX)
                x = this.area.getHeight() - this.content.getHeight() + this.options.overScrollX
            this.pos.x = x;
            this.content.setStyle({
                top: x+'px'
            });
        },
        moveToY: function(y){
            if(!document.loaded)
                Element.observe(window,'load',this.moveToY.bind(this,y));
            if(this.area.getWidth() <= this.content.getWidth() && y > 0 + this.options.overScrollY)
                y = 0 + this.options.overScrollY;
            else if(this.area.getWidth() <= this.content.getWidth() && y < this.area.getWidth() - this.content.getWidth() - this.options.overScrollY)
                y = this.area.getWidth() - this.content.getWidth() - this.options.overScrollY;
            else if(this.area.getWidth() > this.content.getWidth() && y < 0 + this.options.overScrollY)
                y = 0 + this.options.overScrollY;
            else if(this.area.getWidth() > this.content.getWidth() && y > this.area.getWidth() - this.content.getWidth() - this.options.overScrollY)
                y = this.area.getWidth() - this.content.getWidth() - this.options.overScrollY
            this.pos.y = y;
            this.content.setStyle({
                left: y+'px'
            });

            var range = this.area.getWidth() - this.content.getWidth() - 2*this.options.overScrollY;
            var perc = (parseInt(this.content.getStyle('left'))-this.options.overScrollY) / range *100;

            var left = (this.options.SliderY[0].getWidth() - this.options.SliderY[1].getWidth()) * (perc/100);
            this.options.SliderY[1].setStyle({
                left:left+'px'
            });

        },
        moveTo: function(x,y){
            this.moveToX(x);
            this.moveToY(y);
        },
        moveByX: function(x){
            this.moveToX(eval(this.pos.x+'+'+x));
        },
        moveByY: function(y){
            this.moveToY(eval(this.pos.y+'+'+y));
        },
        moveBy: function(x,y){
            this.moveByX(x);
            this.moveByY(y);
        },
        startMovingX: function(x){
            if(this.periodicalExecuter.x)
                this.periodicalExecuter.x.stop();
            this.periodicalExecuter.x = new PeriodicalExecuter(this.moveByX.bind(this,x),0.05);
        },
        startMovingY: function(y){
            if(this.periodicalExecuter.y)
                this.periodicalExecuter.y.stop();
            this.periodicalExecuter.y = new PeriodicalExecuter(this.moveByY.bind(this,y),0.05);
        },
        stopMovingX: function(){
            if(this.periodicalExecuter.x)
                this.periodicalExecuter.x.stop();
        },
        stopMovingY: function(){
            if(this.periodicalExecuter.y)
                this.periodicalExecuter.y.stop();
        },
        scroll: function(event){
            this.moveByX(19/event.scroll())
            event.stop();
        },
        startSlidingY: function(event){
            this.startLeft = parseInt(this.options.SliderY[1].getStyle('left'));
            this.mouseLeft = event.pointerX();
            if(this.funcWrapperY)
                Element.stopObserving(window,'mousemove',this.funcWrapperY);
            this.funcWrapperY = this.slidingY.bindAsEventListener(this);
            Element.observe(window,'mousemove',this.funcWrapperY);
            event.preventDefault();
            if(Prototype.Browser.IE){
                window.document.onmousemove = this.funcWrapperY;
                window.document.onselectstart = function(){return false};
                window.document.onmouseup = this.stopSlidingY.bindAsEventListener(this);
            }
        },
        stopSlidingY: function(){
            if(Prototype.Browser.IE){
                window.document.onmousemove = null;
                window.document.onselectstart = null;
            }
            Element.stopObserving(window,'mousemove',this.funcWrapperY);
            this.funcWrapperY = null;
        },
        slidingY: function(event){
            var x = Event.pointer(event).x;
            var left = this.startLeft + (x - this.mouseLeft);
            if(left < 0){
                left = 0;
            }else if(left > this.options.SliderY[0].getWidth() - this.options.SliderY[1].getWidth()){
                left = this.options.SliderY[0].getWidth() - this.options.SliderY[1].getWidth();
            }
            this.options.SliderY[1].setStyle({
                left: left+'px'
            });
            var range = this.options.SliderY[0].getWidth() - this.options.SliderY[1].getWidth();
            var perc = parseInt(this.options.SliderY[1].getStyle('left')) / range * 100;
            this.moveToY(this.options.overScrollY + (this.area.getWidth() - this.content.getWidth() - 2*this.options.overScrollY) * perc / 100);
            //event.stop();
            return true;
        },
        startSlidingX: function(event){
            this.startTop = parseInt(this.options.SliderX[1].getStyle('top'));
            this.mouseTop = event.pointerY();
            if(this.funcWrapperX)
                Element.stopObserving(window,'mousemove',this.funcWrapperX);
            this.funcWrapperX = this.slidingX.bindAsEventListener(this);
            event.preventDefault();
            Element.observe(window,'mousemove',this.funcWrapperX);
        },
        stopSlidingX: function(){
            Element.stopObserving(window,'mousemove',this.funcWrapperX);
            this.funcWrapperX = null;
        },
        slidingX: function(event){
            var top = this.startTop + (event.pointerY() - this.mouseTop);
            if(top < 0){
                top = 0;
            }else if(top > this.options.SliderY[0].getHeight() - this.options.SliderY[1].getHeight()){
                top = this.options.SliderY[0].getHeight() - this.options.SliderY[1].getHeight();
            }
            this.options.SliderX[1].setStyle({
                top: top+'px'
            })
            var range = this.options.SliderX[0].getHeight() - this.options.SliderX[1].getHeight();
            var perc = parseInt(this.options.SliderX[1].getStyle('top')) / range * 100;
            this.moveToX(this.options.overScrollX + (this.area.getHeight() - this.content.getHeight() - 2*this.options.overScrollX) * perc / 100);
            event.stop();
            return true;
        }
    });

    ImageChanger = Class.create({
        initialize: function(element,images){
            this.element = $(element);
            this.original = this.element.src;
            this.images = images;
            this.options = {
                swapBack: true
            };
            Object.extend(this.options, arguments[2] || {});
            if(images.mouseover){
                this.element.observe('mouseover',this.changeImage.bind(this,'mouseover'));
                if(this.options.swapBack)
                    this.element.observe('mouseout',this.changeImage.bind(this,'mouseout',true));
            }
            if(images.mousedown){
                this.element.observe('mousedown',this.changeImage.bind(this,'mousedown'));
                if(this.options.swapBack)
                    this.element.observe('mouseup',this.changeImage.bind(this,'mouseup',true));
            }
            if(images.mouseout){
                this.element.observe('mouseout',this.changeImage.bind(this,'mouseout'));
            }
            if(images.mouseup){
                this.element.observe('mouseup',this.changeImage.bind(this,'mouseup'));
            }
        },
        changeImage: function(type,swapBack){
            switch(type){
                case 'mouseover':
                case 'mousedown':
                    this.element.src = this.images[type];
                    break;
                case 'mouseout':
                    if(swapBack == true)
                        this.element.src = this.original;
                    else
                        this.element.src = this.images.mouseout;
                    break;
                case 'mouseup':
                    if(swapBack == true){
                        if(this.images.mouseover)
                            this.element.src = this.images.mouseover;
                        else
                            this.element.src = this.original;
                    }else
                        this.element.src = this.images.mouseup;
                    break;
            }
        }
    });

    function show_tooltip(sTooltip){
        $('tooltip').update(sTooltip).show();
    }
    function hide_tooltip(){
        $('tooltip').hide();
    }

    RatingOptions = Class.create({
        initialize: function(oObject,aImages,aOptions){
            this.oObject = oObject;
            this.aImages = aImages;

            this.options = {
                ignoreFirst: false
            }

            Object.extend(this.options, aOptions || {});

            this.oValueField = null;
            this.sName = null;
            this.aValues = new Array();
            this.sValue = null;
            this.aValueImages = new Array();

            this.iCurrent = -1;

            this._parseSource();
            this._insertElements();
        },
        _parseSource: function(){
            var aElements = this.oObject.getElementsByTagName('input');
            for(var i=0;i<aElements.length;i++){
                if(aElements[i].getAttribute('type').toLowerCase() == 'radio'){
                    if(this.sName == null){
                        this.sName = aElements[i].getAttribute('name');
                    }
                    if(aElements[i].getAttribute('name') == this.sName){
                        this.aValues.push(aElements[i].getAttribute('value'));
                    }
                }
            }
        },
        _insertElements: function(){
            for(var i=this.oObject.childNodes.length-1;i>=0;i--){
                Element.remove(this.oObject.childNodes[i]);
            }
            var oContent = null;
            if(this.oObject.tagName.toLowerCase() == 'tr')
            {
                oContent = new Element('td').setStyle({
                    textAlign: 'center'
                });
                this.oObject.insert({
                    bottom: oContent
                });
            }
            else
            {
                oContent = this.oObject;
            }

            this.oValueField = new Element('input',{
                type: 'hidden',
                name: this.sName,
                value: this.aValues[0]
            });

            oContent.insert({bottom:this.oValueField});

            var start = (this.options.ignoreFirst) ? 1 : 0;
            for(var i=start;i<this.aValues.length;i++){
                this.aValueImages.push(new Element('img',{
                        src: this.aImages[0]
                    }).observe('mouseover',this.mouseover.bind(this,this.aValueImages.length))
                      .observe('mouseout',this.mouseout.bind(this))
                      .observe('click',this.click.bind(this,this.aValueImages.length))
                );
                oContent.insert({
                    bottom: this.aValueImages.last()
                });
            }
        },
        mouseover: function(iI){
            this._setImages(iI);
        },
        mouseout: function(){
            this._setImages(this.iCurrent);
        },
        click: function(iI){
            if(this.iCurrent == iI)
                this.iCurrent = -1;
            else
                this.iCurrent = iI;
            this._setImages(this.iCurrent);

            var x = (this.options.ignoreFirst) ? 1 : 0;

            this.oValueField.setAttribute('value',this.aValues[(this.iCurrent+x)]);
        },
        _setImages: function(iI){
            for(var i=0;i<this.aValueImages.length;i++){
                var x = (i<=iI) ? 1 : 0;
                this.aValueImages[i].setAttribute('src',this.aImages[x]);
            }
        }
    });

CPopup = Class.create({
    initialize: function(){
        this.loaded = false;
        this.options = {
            bgColor: '#fff',
            bgOpacity: '0.5',
            bgZIndex: 1000,
            clickonbackground: false,
            autoload: false,
            contentHeight: 'auto',
            contentWidth: 'auto',
            contentBgColor: '#fff',
            contentBorder: '1px solid black',
            contentZIndex: 1001,
            overflow: 'hidden',
            closeButton: true,
            shadow: true,
            speed: 0.2,
            position: (parseInt(navigator.appVersion) < 5) ? 'absolute' : 'fixed',
            posX: 'auto',
            posY: 'auto',
            closeable: true,
            color: '#000'
        }
        Object.extend(this.options, arguments[0] || {});
        this.elements = {
            bg: null,
            window: null,
            wrapper: null,
            shadow: null
        };
        if(document.loaded)
            this._insertElements();
        else
            Event.observe(window,'load',this._insertElements.bind(this));
    },
    _insertElements: function(){
        var left, top;
        if(this.options.posX == 'auto')
            left = Math.round((parseInt(document.viewport.getWidth())-parseInt(this.options.contentWidth))/2)+'px'
        else
            left = this.options.posX;

        if(this.options.posY == 'auto')
            top = Math.round((parseInt(document.viewport.getHeight())-parseInt(this.options.contentHeight))/2)+'px';
        else
            top = this.options.posY;

        this.elements.bg = new Element('div', {});
        this.elements.bg.setStyle({
            backgroundColor: this.options.bgColor,
            position: this.options.position,
            top: '0px',
            left: '0px',
            height: '100%',
            width: '100%',
            opacity: this.options.bgOpacity,
            zIndex: this.options.bgZIndex
        });

        if(!this.options.autoload)
            this.elements.bg.hide();

        if(this.options.clickonbackground)
            Event.observe(this.elements.bg,'click',this.hide.bind(this));

//        document.getElementsByTagName('body')[0].insert({
//            bottom: this.elements.bg
//        });
            document.getElementsByTagName('body')[0].appendChild(this.elements.bg);

        this.elements.window = new Element('div', {});
        this.elements.window.setStyle({
            backgroundColor: this.options.contentBgColor,
            position: this.options.position,
            top: top,
            left: left,
            border: this.options.contentBorder,
            zIndex: this.options.contentZIndex,
            height: this.options.contentHeight,
            width: this.options.contentWidth,
            overflow: this.options.overflow,
            color: this.options.color
        });

        this.elements.window.hide();

        this.elements.wrapper = new Element('div');

        this.elements.window.insert({
            top: this.elements.wrapper
        })

        if(this.options.closeButton)
        {
            this.elements.closeButton = new Element('img',{
                src: '/images/suchagenten/delete.png',
                alt: 'Close',
                id: 'clo'
            }),
            this.elements.closeButton.setStyle({
                position: 'absolute',
                top: '3px',
                right: '2px',
                cursor: 'pointer'
            });

            Event.observe(this.elements.closeButton,'click',this.hide.bind(this));
            this.elements.window.insert({
                bottom: this.elements.closeButton
            })
        }

//        document.getElementsByTagName('body')[0].insert({
//            bottom: this.elements.window
//        });
document.getElementsByTagName('body')[0].appendChild(this.elements.window);

        if(this.options.shadow)
        {
            this.elements.shadow = new Element('div', {});
            this.elements.shadow.setStyle({
                backgroundColor: '#000',
                position: this.options.position,
                top: parseInt(top)+8+'px',
                left: parseInt(left)+8+'px',
                zIndex: (this.options.contentZIndex-1),
                height: this.options.contentHeight,
                width: this.options.contentWidth,
                opacity: 0.5
            });

            this.elements.shadow.hide();

//            document.getElementsByTagName('body')[0].insert({
//                bottom: this.elements.shadow
//            });
        document.getElementsByTagName('body')[0].appendChild(this.elements.shadow);
        }

        if(this.options.autoload)
        {
            setTimeout(this._position.bind(this), 1000);
            Effect.Grow(this.elements.window,{duration:this.options.speed});
            if(this.options.shadow)
                Effect.Grow(this.elements.shadow,{duration:this.options.speed});
        }
        Event.observe(window,'resize',this._position.bind(this));
        this.loaded = true;
    },
    hide: function(){
        //alert("wird geschlossen");
        if(this.options.closeable != true)
            return;
        this.elements.bg.hide();
        this.elements.window.hide();
        if(this.options.shadow)
            this.elements.shadow.hide();
    },
    show: function(){
        this.elements.bg.show();
        Effect.Grow(this.elements.window,{duration:this.options.speed});
        if(this.options.shadow)
            Effect.Grow(this.elements.shadow,{duration:this.options.speed});
    },
    setContent: function(content){
        if(!document.loaded && !arguments[1])
        {
            Event.observe(window,'load',this.setContent.bind(this,content,true));
            return;
        }
        if(!this.loaded)
        {
            setTimeout(this.setContent.bind(this,content),100);
            return;
        }
        if(content && content.toElement)
            content = content.toElement();
        else if(!Object.isElement(content))
            content = Object.toHTML(content);
        this.elements.wrapper.innerHTML = '';
        this.elements.wrapper.insert({
            bottom: content
        });
        //this.addCloseButton();
        this._position();
    },
    _position: function(){
        var top, left;
        if(this.options.posX == 'auto')
            left = Math.round((parseInt(document.viewport.getWidth())-parseInt(this.options.contentWidth))/2)+'px'
        else
            left = this.options.posX;

        if(this.options.posY == 'auto')
            top = Math.round((parseInt(document.viewport.getHeight())-parseInt(this.options.contentHeight))/2)+'px';
        else
            top = this.options.posY;

        this.elements.shadow.setStyle({
            height: this.elements.window.getHeight()+'px'
        });
        this.elements.shadow.setStyle({
            width: this.elements.window.getWidth()+'px'
        });
        this.elements.window.setStyle({
            top: top,
            left: left
        });
        this.elements.shadow.setStyle({
            top: parseInt(top)+8+'px',
            left: parseInt(left)+8+'px'
        });
    }/*,
    addCloseButton: function(){
        if(!Object.isElement(this.elements.closeButton))
            return;
        this.elements.window.insert({
            top: this.elements.closeButton
        });
    }*/
});

MouseOver = Class.create({
    src: null,
    element: null,
    timeout: null,
    mouseover: false,
    timer: null,
    initialize: function(src, element, timeout) {
        this.src = $(src);
        this.element = $(element);
        this.timeout = timeout;

        this.src.observe("mouseover", this.actionPerformed.bindAsEventListener(this));
        this.src.observe("mouseout", this.actionPerformed.bindAsEventListener(this));

        this.element.observe("mouseover", this.actionPerformed.bindAsEventListener(this));
        this.element.observe("mouseout", this.actionPerformed.bindAsEventListener(this));
    },
    actionPerformed: function(e) {
        var event = Event.extend(e);
        
        if(event.type == "mouseover") {
            this.element.show();
            if(this.timer != null)
                window.clearTimeout(this.timer);
        } else if(event.type == "mouseout") {
            if(this.timer != null)
                window.clearTimeout(this.timer);
            this.timer = window.setTimeout(function(){
                this.element.hide();
            }.bind(this), this.timeout);
        }
    }
});

InlineEditor = Class.create({
    initialize: function(element,options) {
        this.element = $(element);

        this.options = {
            filter: /[^.]/,
            inputStyle: {
                width: '150px'
            },
            onAccept: function() {},
            onCancel: function() {}
        }

        this.tmpText = '';

        Object.extend(this.options, options || {});

        this.element.observe("click", this.actionPerformed.bindAsEventListener(this));

        this.input = null;
    },
    actionPerformed: function(e) {
        var event = Event.extend(e);

        if(event.element() == this.element && event.type == "click") {
            this.tmpText = this.element.innerHTML;
            this.element.innerHTML = '';

            this.input = new Element("input").setStyle(this.options.inputStyle).observe("keypress",this.actionPerformed.bindAsEventListener(this));
            
            this.element.insert(this.input);
            this.input.focus();

            this.input.observe("blur", this.actionPerformed.bind(this));
        } else if(event.element() == this.input && event.type == "keypress") {
            if(event.keyCode == Event.KEY_ESC) {
                this.element.innerHTML = this.tmpText;
                this.options.onCancel(this);
            } else if(event.keyCode == Event.KEY_RETURN) {
                this.element.innerHTML = this.input.value;
                this.options.onAccept(this);
            } else {
                window.setTimeout(function(){this.input.value = this.input.value.replace(this.options.filter,'');}.bind(this),10);
            }
        } else if(event.element() == this.input && event.type == "blur") {
            this.element.innerHTML = this.tmpText;
            this.options.onCancel(this);
        }
    }
});


var ClipPreview = Class.create({
    initialize: function(element, clip, dimension, images) {
       this.element = $(element);
       this.clip = clip;
       this.dimension = dimension;
       this.images = images;
       this.curImage = 1;

       this.interval = null;


       this.element.observe('mouseover', this.actionPerformed.bindAsEventListener(this));
       this.element.observe('mouseout', this.actionPerformed.bindAsEventListener(this));


       $A(images).each(function(image){
           Preload(['/videos/preview.php?clip_id='+this.clip+'&dimension='+this.dimension+'&picture='+image])
       }.bind(this));

       this.element.setStyle({
           backgroundImage: 'url(/videos/preview.php?clip_id='+this.clip+'&dimension='+this.dimension+'&picture='+this.images[0]+')'
       });

       this.element.setStyle({
           position: 'relative',
           cursor: 'pointer'
       });

       this.element.insert({
           bottom: new Element('img',{
               src: '/images/play.png'
           }).setStyle({
               position: 'absolute',
               right: '10px',
               bottom: '10px',
               border: 0
           })
       });
    },
    actionPerformed: function(e) {
        var event = Event.extend(e);
        if(event.type == 'mouseover') {
            this.interval = window.setInterval(this.nextImage.bind(this), 1000);
        } else if(event.type == 'mouseout') {
            if(this.interval != null)
                window.clearInterval(this.interval);
            this.element.setStyle({
                backgroundImage: 'url(/videos/preview.php?clip_id='+this.clip+'&dimension='+this.dimension+'&picture='+this.images[0]+')'
            });
            this.curImage = 1;
        }
    },
    nextImage: function() {
        if(this.curImage > this.images.length-1)
            this.curImage = 0;
        this.element.setStyle({
            backgroundImage: 'url(/videos/preview.php?clip_id='+this.clip+'&dimension='+this.dimension+'&picture='+this.images[this.curImage++]+')'
        });
        
    }
});

function $N(name, doc) {
    return $A((doc || document).getElementsByName(name)).collect(function(element){return $(element)});
}
function $TN(name, doc) {
    return $A((doc || document).getElementsByTagName(name)).collect(function(element){return $(element)});
}

function setupFreigabeEditor(el, url, options) {
    var editor=new Ajax.InPlaceEditor(el, url, options);
    Object.extend(editor, {
        createEditField: function() {
            var text=this.getText();

            var field=document.createElement("select");
            field.name="value";
            field.style.width = '175px';

            this.editField=field;
            this._form.appendChild(this.editField);
            this._controls.editor = field;
            ['Niemanden','Meine Kontakte', 'Meine Favoriten', 'Kontakte und Favoriten', 'Alle Mitglieder'].each(function(name, index) {
                var op=document.createElement("option");
                op.value= index;
                op.text= name;
                if(window.ActiveXObject) {
                    field.options.add(op);
                } else {
                    field.appendChild(op);
                }

                // Select the current item
                if(op.text == text) {
                    field.selectedIndex=index;
                }
            });
        }
    });
}

Ajax.InPlaceEditorSelect = Class.create(Ajax.InPlaceEditor, {
    initialize: function($super, element, url, values, options) {
        $super(element, url, options);
        this.values = $A(values || {});
    },
    createEditField: function() {
        var text = this.getText();
        var field = new Element('select', {
            name: this.options.paramName
        }).setStyle({
            width: (this.options.size || 100)+'px'
        }).addClassName('editor_select');
        if(this.options.submitOnBlur)
            field.observe('blur', this._boundSubmitHandler);
        this.values.each(function(name, index) {
            var option = document.createElement('option');
            option.value = index;
            option.text = name;
            if(window.ActiveXObject) {
                field.options.add(option);
            } else {
                field.appendChild(option);
            }
        })
        this._controls.editor = field;
        this._form.appendChild(this._controls.editor);
    }
});

Object.extend(Element, {
    innerWrap: function(element, wrapper, attributes) {
        element = $(element);
        if(Object.isElement(wrapper)) $(wrapper).writeAttributes(attributes || {});
        else if(Object.isString(wrapper)) wrapper = new Element(wrapper, attributes);
        else wrapper = new Element('div', attributes);
        /*element.descendants().each(function(childElement){
            wrapper.appendChild(childElement);
            childElement.remove();
        });*/
        wrapper.innerHTML = element.innerHTML;
        element.innerHTML = '';
        element.appendChild(wrapper);
        return wrapper;
    }
});

var Dozer = Class.create({
    initialize: function(element, options) {
        this.options = {
            start: 0,
            length: 5,
            duration: 1,
            tagName: 'li',
            align: 'vertical',
            hideControlsIfNotNeeded: true,
            onReachFirst: function(){},
            onReachEnd: function(){},
            onMoveUp: function(){},
            onMoveDown: function(){}
        }

        this.element = element = $(element);

        Object.extend(this.options, options || {});

        this.query = [];

        this.executing = false;

        this.position = 0;

        this.elements = $TN(this.options.tagName, this.element);

        this.moveUpElement = this.elements.shift();
        this.moveDownElement = this.elements.pop();

        this.originalDimensions = [];

        this.elements.each(function(element, index) {
            Element.innerWrap(element, 'div', {style:'position:absolute;left:0px'});
            this.originalDimensions[index] = element.getDimensions();
        }.bind(this));

        if(this.options.hideControlsIfNotNeeded && this.elements.length <= this.options.length) {
            [this.moveUpElement,this.moveDownElement].each(function(element) {
                element.setStyle({
                    display: 'none' //visibility: 'hidden'
                });
            });
        }

        this.elements.slice(this.options.length).each(function(element){
            element.setStyle({
                width: '0px'
            });
            element.hide();
        });

        //this.moveUpElement.observe('click', this.moveUp.bind(this));
        //this.moveDownElement.observe('click', this.moveDown.bind(this));
        this.moveUpElement.observe('click', this.move.bind(this,'up'));
        this.moveDownElement.observe('click', this.move.bind(this,'down'));
    },
    move: function(type) {
        type = type.toLowerCase();
        if(!['up','down'].include(type))
            return;
        if(this.executing) {
            this.query.push(type);
            return;
        }
        this.executing = true;
        if(type == 'up' && this.position <= 0) {
            this.fireEvent('onReachFirst');
            this.executing = false;
            this.query = this.query.without('up');
            return;
        } else if(type == 'down' && this.position+this.options.length >= this.elements.length) {
            this.fireEvent('onReachEnd');
            this.executing = false;
            this.query = this.query.without('down');
            return;
        }
        this.fireEvent('onMove'+type.capitalize());
        var align = (this.options.align == 'horizontal') ? 'height' : 'width';
        var upper = (type == 'up') ? this.position-1 : this.position;
        var lower = (type == 'up') ? this.position+this.options.length-1 : this.position+this.options.length;
        [upper, lower].each(function(pos, index) {
            var left = (index > 0) ? '0px' : '';
            var right = (index > 0) ? '' : '0px';
            this.elements[pos].show().firstChild.setStyle({
                top: left,
                bottom: right,
                left: left,
                right: right
            });
        }.bind(this));
        new Effect.Parallel([
            new Effect.Morph(this.elements[upper], {
                style:align+':'+((type=='up')?this.originalDimensions[upper][align]:0)+'px',
                sync:true
            }),
            new Effect.Morph(this.elements[lower], {
                style:align+':'+((type=='up')?0:this.originalDimensions[lower][align])+'px',
                sync:true
            })
        ],{
            duration: this.options.duration,
            afterFinish: function(pos) {
                this.elements[pos].hide();
                this.executing = false;
                this.processQuery();
            }.bind(this, (type=='up')?lower:upper)
        });
        this.position += (type=='up') ? -1 : 1;
    },
    fireEvent: function(eventType) {
        if(typeof this.options[eventType] == 'function')
            this.options[eventType]();
    },
    processQuery: function() {
        if(this.query.length == 0)
            return;
        this.move(this.query.shift());
    }
});

var Center = Class.create({
    initialize: function(element) {
        this.element = $(element);
        
        this.parent = $(this.element.parentNode);

        this.parent.makePositioned();

        this.element.absolutize();

        this.onResize();

        this.parent.observe('resize', this.onResize.bind(this));
    },
    onResize: function() {
        var top = parseInt((this.parent.getHeight() - this.element.getHeight()) / 2);
        var left = parseInt((this.parent.getWidth() - this.element.getWidth()) / 2);

        this.element.setStyle({
            top: top+'px',
            left: left+'px'
        });
    }
});

var Preload = function(images) {
    $A(images).each(function(image) {
        var img = new Image();
        img.src = image;
    });
}

var CoreEvent = Class.create({
    initialize: function(source, type, text) {
        this.source = source;
        this.type = type;
        this.text = text || '';
        this.time = new Date();
    },
    getSource: function() {
        return this.source;
    },
    getType: function() {
        return this.type;
    },
    getText: function() {
        return this.text;
    },
    getTime: function() {
        return this.time;
    }
});

var ChangeEvent = Class.create(CoreEvent, {
    initialize: function($super, source, text) {
        $super(source, 'ChangeEvent', text);
    }
});
var UpdateEvent = Class.create(CoreEvent, {
    initialize: function($super, source, text) {
        $super(source, 'UpdateEvent', text);
    }
});
var ResizeEvent = Class.create(CoreEvent, {
    initialize: function($super, source, text) {
        $super(source, 'ResizeEvent', text);
    }
});
var VisibilityEvent = Class.create(CoreEvent, {
    initialize: function($super, source, text) {
        $super(source, 'VisibilityEvent', text);
    }
});
var MovingEvent = Class.create(CoreEvent, {
    initialize: function($super, source, text, x, y) {
        $super(source, 'MovingEvent', text);
        this.x = x;
        this.y = y;
    }
});

var EventBus = {
    observer: {},
    registerObserver: function(type, observer) {
        if(!Object.isFunction(observer.notify))
            throw "Observe must own a notify-Method";
        if(!Object.isArray(EventBus.observer[type]))
            EventBus.observer[type] = [];
        EventBus.observer[type].push(observer);
    },
    removeObserver: function(type, observer) {
        if(!Object.isArray(EventBus.observer[type]))
            return;
        EventBus.observe[type] = EventBus.observe[type].without(observer);
    },
    fireEvent: function(type, event) {
        if(!(event instanceof CoreEvent))
            throw "event must be a subclass of CoreEvent";
        if(!Object.isArray(EventBus.observer[type]))
            return;
        EventBus.observer[type].invoke('notify', event);
    }
}

var TestObserver = Class.create({
    initialize: function(num) {
        this.num = num;
        EventBus.registerObserver('testEvents', this);
    },
    notify: function(evt) {
        console.log('TestObserver'+this.num+' - '+ evt.getType()+evt.getText());
    }
});

var TestSubject = Class.create({
    initialize: function() {
        setTimeout(this.fire.bind(this, 1), 2000);
        setTimeout(this.fire.bind(this, 2), 1000);
        setTimeout(this.fire.bind(this, 3), 3500);
    },
    fire: function(num) {
        EventBus.fireEvent('testEvents', new UpdateEvent(this, num));
    }
});


var Frame = Class.create({
    frame: null,
    initialize: function(options) {
        this.options = {
            draggable: false,
            position: 'absolute',
            top: '0px',
            left: '0px',
            height: 'auto',
            width: 'auto'
        };
        Object.extend(this.options, options || {});
        this._insert();
    },
    _insert: function() {
        this.frame = new Element('div');
        var style = {
            position: this.options.position,
            top: this.options.top,
            left: this.options.left,
            height: this.options.height,
            width: this.options.width
        };
        Object.extend(style, this.options.style || {});
        this.frame.setStyle(style);
        this.frame.addClassName(this.options.classNames || '');
        this._makeDraggable();
        $TN('body')[0].appendChild(this.frame);
    },
    _makeDraggable: function() {
        if(!this.options.draggable) return;
        var options = {
            scroll: true,
            onStart: this.onDragStart.bind(this),
            onDrag: this.onDrag.bind(this),
            change: this.onDragChange.bind(this),
            onEnd: this.onDragEnd.bind(this)
        }
        Object.extend(options, this.options.draggableOptions || {})
        this.draggable = new Draggable(this.frame, options);
    },
    remove: function() {

    },
    setContent: function(content) {
        this.frame.update(content);
        EventBus.fireEvent('FrameUpdate', new UpdateEvent(this, 'updateContent'));
    },
    setVisible: function(visible) {
        this.frame[visible ? 'show' : 'hide']();
    },
    setSize: function(width, height) {
        if(/^\d+$/.match(width)) width = width+'px';
        if(/^\d+$/.match(height)) height = height+'px';
        this.frame.setStyle({
            width: width,
            height: height
        });
    },
    setPosition: function(left, top) {
        if(/^\d+$/.match(top)) top = top+'px';
        if(/^\d+$/.match(left)) left = left+'px';
        this.frame.setStyle({
            left: left,
            top: top
        });
    },
    onDragStart: function() {
        EventBus.fireEvent('FrameMoving', new MovingEvent(this, 'dragStart', this.frame.getStyle('left'), this.frame.getStyle('top')));
    },
    onDrag: function() {
        EventBus.fireEvent('FrameMoving', new MovingEvent(this, 'dragging', this.frame.getStyle('left'), this.frame.getStyle('top')));
    },
    onDragChange: function(draggable) {
        EventBus.fireEvent('FrameMoving', new MovingEvent(this, 'dragChange', this.frame.getStyle('left'), this.frame.getStyle('top')));
    },
    onDragEnd: function() {
        EventBus.fireEvent('FrameMoving', new MovingEvent(this, 'dragEnd', this.frame.getStyle('left'), this.frame.getStyle('top')));
    }
});

/*var ToolTip = Class.create(Frame, {
    showTimeout: null,
    hideTimeout: null,
    initialize: function($super, element, text, options) {
        this.element = $(element);
        this.subOptions = {
            adjustment: 'toptop-left',
            margin: 5,
            offset: {
                x: 0,
                y: 0
            },
            showDelay: 0.15,
            hideDelay: 0.3,
            closeButton: false,
            showOn: 'mouseover',
            hideOn: 'mouseout',
            vars: {},
            hideOthers: false,
            hook: true,
            imgDir: '/images/tooltips/'
        };
        Object.extend(this.subOptions, options);
        this._prepareAdjustment();
        $super({
            left: '0px',
            top: '0px',
            width: '200px',
            classNames: 'tooltip',
            style: {
                display: 'none'
            }
        });
        this._prepare();
        this.text = text;
        ToolTips.registerTooltip(this);
    },
    _prepare: function() {
        if(this.subOptions.showOn !== false)
            this.element.observe(this.subOptions.showOn, this.show.bind(this));
        if(this.subOptions.hideOn !== false)
            this.element.observe(this.subOptions.hideOn, this.hide.bind(this));
        this.content = new Element('div');
        this.frame.update(this.content);
        if(this.subOptions.closeButton) {
            this.content.setStyle({
                marginTop: '23px'
            });
            this.closeButton = new Element('img', {
                src: '/images/suchagenten/delete.png',
                height: 21,
                width: 21,
                alt: 'Schließen',
                title: 'Schließen'
            }).setStyle({
                position: 'absolute',
                top: '1px',
                right: '1px',
                cursor: 'pointer'
            }).observe('click', function(event){
                if(this.showTimeout)
                    window.clearTimeout(this.showTimeout);
                this.setVisible(false);
            }.bindAsEventListener(this));
            this.frame.insert({
                top: this.closeButton
            });
        }
        if(this.subOptions.hook) {
            this.hook = new Element('img', {
                src: this.subOptions.imgDir+this._getHookInfo().image,
                alt: ''
            }).setStyle({
                position: 'absolute',
                left: this._getHookInfo().left,
                top: this._getHookInfo().top,
                right: this._getHookInfo().right,
                bottom: this._getHookInfo().bottom
            });
            this.frame.insert({
                bottom: this.hook
            });
            this.subOptions.offset.x += 12;
            this.subOptions.offset.y += 12;
        }
    },
    _getHookInfo: function() {
        switch(this.subOptions.adjustment) {
            case 'toptop-leftleft':
            case 'toptop-right':
                return {
                    image: 'bottom-right.png',
                    top: null,
                    left: null,
                    right: '10%',
                    bottom: '-13px'
                };
                break;
            case 'toptop-left':
            case 'toptop-rightright':
                return {
                    image: 'bottom-left.png',
                    top: null,
                    left: '10%',
                    right: null,
                    bottom: '-13px'
                };
                break;
            case 'toptop-center':
                return {
                    image: 'bottom-center.png',
                    top: null,
                    left: null,
                    right: '50%',
                    bottom: '-13px'
                };
                break;
            case 'bottombottom-leftleft':
            case 'bottombottom-right':
                return {
                    image: 'top-right.png',
                    top: null,
                    left: null,
                    right: '10%',
                    bottom: '-13px'
                };
                break;
            case 'bottombottom-left':
            case 'bottombottom-rightright':
                return {
                    image: 'top-left.png',
                    top: null,
                    left: null,
                    right: '10%',
                    bottom: '-13px'
                };
                break;
            case 'bottombottom-center':
                return {
                    image: 'top-center.png',
                    top: null,
                    left: null,
                    right: '10%',
                    bottom: '-13px'
                };
                break;
            case 'top-leftleft':
                return {
                    image: 'right-bottom.png',
                    top: null,
                    left: null,
                    right: '10%',
                    bottom: '-13px'
                };
            case 'middle-leftleft':
                return {
                    image: 'right-middle',
                    top: null,
                    left: null,
                    right: '10%',
                    bottom: '-13px'
                };
            case 'bottom-leftleft':
                return {
                    image: 'right-top.png',
                    top: null,
                    left: null,
                    right: '10%',
                    bottom: '-13px'
                };
            case 'top-rightright':
                return {
                    image: 'left-bottom.png',
                    top: null,
                    left: null,
                    right: '10%',
                    bottom: '-13px'
                };
            case 'middle-rightright':
                return {
                    image: 'left-middle.png',
                    top: null,
                    left: null,
                    right: '10%',
                    bottom: '-13px'
                };
            case 'bottom-rightright':
                return {
                    image: 'left-top.png',
                    top: null,
                    left: null,
                    right: '10%',
                    bottom: '-13px'
                };
        }
    },
    show: function() {
        if(this.subOptions.hideOthers)
            ToolTips.hideAll();
        if(/^\d+$/.match(this.text)) {
            new Ajax.Request('/ajax/getTooltip.php', {
                method: 'post',
                parameters: {
                    id: this.text
                },
                onSuccess: function(t) {
                    this.text = t.responseText;
                    this.setContent(this.text);
                    this._reposition();
                }.bind(this)
            });
            this.text = 'Loading Tooltip...';
        }
        this.setContent(this.text);
        this._reposition();
        if(this.hideTimeout)
            window.clearTimeout(this.hideTimeout);
        this.showTimeout = window.setTimeout(function(){
            this.setVisible(true);
        }.bind(this), this.subOptions.showDelay*1000);
    },
    hide: function(instant) {
        if(this.showTimeout)
            window.clearTimeout(this.showTimeout);
        this.hideTimeout = window.setTimeout(function(){
            this.setVisible(false);
        }.bind(this), (!Object.isUndefined(instant) && instant === true) ? 0 : this.subOptions.hideDelay*1000);
    },
    setContent: function($super, content) {
        this.content.update(this._parseTemplate(content));
    },
    _parseTemplate: function(text) {
        return text.interpolate(this.subOptions.vars, /(^|.|\r|\n)(__([^_]+)__)/);
    },
    _getLeft: function() {
        var adjustment = this.subOptions.adjustment.split('-');
        switch(adjustment[1]) {
            case 'leftleft':
                return this.element.cumulativeOffset().left - this.frame.getWidth() - this.subOptions.margin - this.subOptions.offset.x;
            case 'left':
                return this.element.cumulativeOffset().left + this.subOptions.offset.x;
            case 'right':
                return this.element.cumulativeOffset().left + this.element.getWidth() - this.frame.getWidth() - this.subOptions.offset.x;
            case 'rightright':
                return this.element.cumulativeOffset().left + this.element.getWidth() + this.subOptions.margin + this.subOptions.offset.x;
            case 'center':
            default:
                return this.element.cumulativeOffset().left + (this.element.getWidth()/2) - (this.frame.getWidth()/2) + this.subOptions.offset.x;
        }
    },
    _getTop: function() {
        var adjustment = this.subOptions.adjustment.split('-');
        switch(adjustment[0]) {
            case 'toptop':
                return this.element.cumulativeOffset().top - this.frame.getHeight() - this.subOptions.margin - this.subOptions.offset.y;
            case 'top':
                return this.element.cumulativeOffset().top + this.subOptions.offset.y;
            case 'bottom':
                return this.element.cumulativeOffset().top + this.element.getHeight() - this.frame.getHeight() - this.subOptions.offset.y;
            case 'bottombottom':
                return this.element.cumulativeOffset().top + this.element.getHeight() + this.subOptions.margin + this.subOptions.offset.y;
            case 'middle':
            default:
                return this.element.cumulativeOffset().top + (this.element.getHeight()/2) - (this.frame.getHeight()/2) + this.subOptions.offset.y;
        }
    },
    _prepareAdjustment: function() {
        var adjustment = this.subOptions.adjustment.split('-');
        if(adjustment.length != 2) {
            this.options.adjustment = 'toptop-right';
            return;
        }
        if(['left','center','right'].include(adjustment[1])) {
            if(!['toptop','bottombottom'].include(adjustment[0])) {
                if(['top','bottom'].include(adjustment[0])) {
                    adjustment[0] = adjustment[0].times(2);
                } else {
                    adjustment[0] = 'toptop';
                }
            }
        }
        this.subOptions.adjustment = adjustment.join('-');
    },
    _reposition: function() {
        this.frame.setStyle({
            left: this._getLeft()+'px',
            top: this._getTop()+'px'
        });
    }
});

var ToolTips = {
    tooltips: [],
    registerTooltip: function(tooltip) {
        if(!(tooltip instanceof ToolTip))
            throw "Only ToolTips will registered";
        ToolTips.tooltips.push(tooltip);
    },
    removeTooltip: function(tooltip) {
        ToolTips.tooltips = ToolTips.tooltips.without(tooltip);
    },
    getTooltips: function() {
        return ToolTips.tooltips;
    },
    hideAll: function() {
        ToolTips.getTooltips().invoke('hide', true);
    }
}

Event.observe(window, 'load', function(event) {
    $$('*[title]').each(function(element) {
        if(/^tooltip:.+:.+$/.match(element.title)) {
            element.title.scan(/^tooltip:(.*):(.*)$/, function(match) {
                new ToolTip(element, match[2], {
                    adjustment: 'toptop-center',
                    offset: {
                        x: 0,
                        y: 0
                    },
                    vars: eval("t="+match[1]+";"),
                    hideOthers: true
                })
            });
            element.title = '';
        }
        else if(/^tooltip:.*$/.match(element.title)) {
            element.title.scan(/^tooltip:(.*)$/, function(match){
                new ToolTip(element, match[1], {
                    adjustment: 'toptop-center',
                    offset: {
                        x: 0,
                        y: 0
                    },
                    hideOthers: true
                });
            });
            element.title = '';
        }
    });
});
*/