var MO = {};
MO.ECARD_SEND = 'Send e-Card';
MO.ECARD_BUBBLE_SEND = 'Send Bubble-It e-Card';
MO.ECARD_HEAD = 'Make your friends happy with a <b>toonpool.com</b> e-Card!';
MO.ECARD_NAME = 'Your name';
MO.ECARD_EMAIL = 'Your e-mail';
MO.ECARD_FRIENDS = 'Your friends';
MO.ECARD_ADD_ONE = 'Add one friend';
MO.ECARD_DEL_ONE = 'Remove one friend';
MO.ECARD_RNAME = 'Name';
MO.ECARD_REMAIL = 'e-mail';
MO.ECARD_TITLE = 'Title';
MO.ECARD_OPTIONAL = 'optional';
MO.ECARD_MSG = 'Message';
MO.ECARD_SENDON = 'Send on';
MO.ECARD_NOTI_SENT = 'tell me when my e-Card has been sent';
MO.ECARD_NOTI_SEEN = 'tell me when my friends have seen my e-Card';
MO.ECARD_BUTTON_SEND = 'send';
MO.ECARD_BUTTON_PREVIEW = 'preview';
MO.ECARD_PRE_HELLO = 'Hello';
MO.ECARD_PRE_TITLE = 'this is your e-Card from';
MO.ECARD_PRE_BUBBLE_TITLE = 'this is your Bubble-It e-Card from';
MO.ECARD_BUTTON_CHANGE = 'change';
MO.ECARD_ERROR = 'Please correct all fields marked in red.\ne-mail addresses have to be valid.';
MO.IMG9_BY = 'by';
MO.FAV_TITLE = 'Add this cartoon to your favorites.';
MO.FAV_WHY = 'why is this a favorite cartoon for you? (recommended)';
MO.FAV_SUBMIT = 'save favorite';
MO.SPAM_TITLE = 'Report';
MO.SPAM_1 = 'Discrimination';
MO.SPAM_2 = 'Copyright Violation';
MO.SPAM_3 = 'False Allegation';
MO.SPAM_4 = 'Duplicate Content';
MO.SPAM_0 = 'Others';
MO.SPAM_REASON = 'Reason (recommended)';
MO.SPAM_SUBMIT = 'submit';
MO.TRANS_TITLE = 'Let everybody<br /><b>understand</b><br />this cartoon.';
MO.TRANS_OTHER = 'Other translations';
MO.TRANS_FIRST = 'no translations available yet.';
MO.TRANS_BY = 'by';
MO.TRANS_DEL = 'Delete this translation?';
MO.TRANS_NEW = 'Your translation';
MO.TRANS_SUBMIT = 'translate';
MO.TRANS_EDIT = 'edit';
MO.TRANS_CHECK1 = 'Please enter a username.';
MO.TRANS_CHECK2 = 'Please enter a valid e-mail address.';
MO.TRANS_CHECK3 = 'Please enter a translation.';
MO.NOUSER_NAME = 'Please enter your name:';
MO.NOUSER_EMAIL = 'Please enter your email-address:';
MO.CONTACT_ADD = 'Add';
MO.CONTACT_TO = 'to your contacts.';
MO.CONTACT_RELOAD = 'Reload Image';
MO.CONTACT_RELOAD1 = 'reload';
MO.CONTACT_ENTER_CODE = 'Enter the code exactly as you see it:';
MO.CONTACT_SUBMIT = 'Save';
MO.CONTACT_DEL = 'Delete %1$s from your contacts?';
MO.CONTACT_DEL_SUBMIT = 'Delete';
MO.COTD_TITLE = 'Daily Cartoon';
MO.COTD_DETAILS = 'Details';
MO.COTD_CLOSE_T = 'Click to close';
MO.COTD_CLOSE = 'close';
MO.COTD_SUB_T = 'Subscribe to the Daily Toon';
MO.COTD_SUB = 'Get the Daily Toon by e-mail!';
MO.ECARD_REAL_POSTCARD = 'Get this ecard as a real postcard.';
MO.RECOMM_HEAD = 'I know someone who might like it!';
MO.IMAGES = 'image(s)';



var FO = {};
FO.PL_NOT_ALLOWED = 'not allowed in';
FO.PL_TO_DEEP = 'too deep nested';
FO.PL_END_TAG = 'end-tag ignored';
FO.PN_END_BEGIN = 'end-tag without begin-tag';
FO.PN_BEGIN_END = 'begin-tag without end-tag';
FO.PT_UNKNOWN = 'unknown tag';
FO.PT_FORBIDDEN = 'forbidden tag';
FO.CF_NEW_T = 'Start new topic';
FO.CF_SUBJECT = 'Subject';
FO.CF_EDIT_P = 'Edit post';
FO.CF_NEW_A = 'Write new post';
FO.CF_MSG = 'Text';
FO.CF_STYLE = 'Style';
FO.CF_PREVIEW = 'Preview';
FO.CF_SUBMIT = 'Send';
FO.CF_CANCEL = 'Cancel';
FO.CF_POST_PREVIEW = 'Preview';
FO.NOUSER_NAME = 'Name';
FO.NOUSER_EMAIL = 'e-mail address';



/*
 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
 * in FIPS PUB 180-1
 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for details.
 */

/*
 * Configurable variables. You may need to tweak these to be compatible with
 * the server-side, but the defaults work in most cases.
 */
var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
var b64pad  = ""; /* base-64 pad character. "=" for strict RFC compliance   */
var chrsz   = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */

/*
 * These are the functions you'll usually want to call
 * They take string arguments and return either hex or base-64 encoded strings
 */
function hex_sha1(s){return binb2hex(core_sha1(str2binb(s),s.length * chrsz));}
function b64_sha1(s){return binb2b64(core_sha1(str2binb(s),s.length * chrsz));}
function str_sha1(s){return binb2str(core_sha1(str2binb(s),s.length * chrsz));}
function hex_hmac_sha1(key, data){ return binb2hex(core_hmac_sha1(key, data));}
function b64_hmac_sha1(key, data){ return binb2b64(core_hmac_sha1(key, data));}
function str_hmac_sha1(key, data){ return binb2str(core_hmac_sha1(key, data));}

/*
 * Perform a simple self-test to see if the VM is working
 */
function sha1_vm_test()
{
  return hex_sha1("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d";
}

/*
 * Calculate the SHA-1 of an array of big-endian words, and a bit length
 */
function core_sha1(x, len)
{
  /* append padding */
  x[len >> 5] |= 0x80 << (24 - len % 32);
  x[((len + 64 >> 9) << 4) + 15] = len;

  var w = Array(80);
  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;
  var e = -1009589776;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;
    var olde = e;

    for(var j = 0; j < 80; j++)
    {
      if(j < 16) w[j] = x[i + j];
      else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
      var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
                       safe_add(safe_add(e, w[j]), sha1_kt(j)));
      e = d;
      d = c;
      c = rol(b, 30);
      b = a;
      a = t;
    }

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
    e = safe_add(e, olde);
  }
  return Array(a, b, c, d, e);

}

/*
 * Perform the appropriate triplet combination function for the current
 * iteration
 */
function sha1_ft(t, b, c, d)
{
  if(t < 20) return (b & c) | ((~b) & d);
  if(t < 40) return b ^ c ^ d;
  if(t < 60) return (b & c) | (b & d) | (c & d);
  return b ^ c ^ d;
}

/*
 * Determine the appropriate additive constant for the current iteration
 */
function sha1_kt(t)
{
  return (t < 20) ?  1518500249 : (t < 40) ?  1859775393 :
         (t < 60) ? -1894007588 : -899497514;
}

/*
 * Calculate the HMAC-SHA1 of a key and some data
 */
function core_hmac_sha1(key, data)
{
  var bkey = str2binb(key);
  if(bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz);

  var ipad = Array(16), opad = Array(16);
  for(var i = 0; i < 16; i++)
  {
    ipad[i] = bkey[i] ^ 0x36363636;
    opad[i] = bkey[i] ^ 0x5C5C5C5C;
  }

  var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz);
  return core_sha1(opad.concat(hash), 512 + 160);
}

/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */
function safe_add(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

/*
 * Bitwise rotate a 32-bit number to the left.
 */
function rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}

/*
 * Convert an 8-bit or 16-bit string to an array of big-endian words
 * In 8-bit function, characters >255 have their hi-byte silently ignored.
 */
function str2binb(str)
{
  var bin = Array();
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < str.length * chrsz; i += chrsz)
    bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (32 - chrsz - i%32);
  return bin;
}

/*
 * Convert an array of big-endian words to a string
 */
function binb2str(bin)
{
  var str = "";
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < bin.length * 32; i += chrsz)
    str += String.fromCharCode((bin[i>>5] >>> (32 - chrsz - i%32)) & mask);
  return str;
}

/*
 * Convert an array of big-endian words to a hex string.
 */
function binb2hex(binarray)
{
  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i++)
  {
    str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) +
           hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8  )) & 0xF);
  }
  return str;
}

/*
 * Convert an array of big-endian words to a base-64 string
 */
function binb2b64(binarray)
{
  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i += 3)
  {
    var triplet = (((binarray[i   >> 2] >> 8 * (3 -  i   %4)) & 0xFF) << 16)
                | (((binarray[i+1 >> 2] >> 8 * (3 - (i+1)%4)) & 0xFF) << 8 )
                |  ((binarray[i+2 >> 2] >> 8 * (3 - (i+2)%4)) & 0xFF);
    for(var j = 0; j < 4; j++)
    {
      if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
      else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
    }
  }
  return str;
}



var crossBrowser = {};
crossBrowser.docEl = (typeof document.compatMode != 'undefined' && document.compatMode != 'BackCompat') ? 'documentElement' : 'body';
crossBrowser.is_ie = navigator.userAgent.toLowerCase().indexOf('msie') != -1;
crossBrowser.is_ie6 = navigator.userAgent.toLowerCase().indexOf('msie 6.') != -1;
crossBrowser.is_ff = navigator.userAgent.toLowerCase().indexOf('firefox') != -1;
crossBrowser.is_opera = navigator.userAgent.toLowerCase().indexOf('opera') != -1;
crossBrowser.is_safari = navigator.userAgent.toLowerCase().indexOf('safari') != -1;

if (window.innerWidth) {
  crossBrowser.getWindowInnerWidth = function() {return window.innerWidth; };
  crossBrowser.getWindowInnerHeight = function() { return window.innerHeight; };
  crossBrowser.getScrollX = function() { return window.pageXOffset; };
  crossBrowser.getScrollY = function() { return window.pageYOffset; };
} else {
  crossBrowser.getWindowInnerWidth = function() { return document[crossBrowser.docEl].clientWidth; };
  crossBrowser.getWindowInnerHeight = function() { return document[crossBrowser.docEl].clientHeight; };
  crossBrowser.getScrollX = function() { return document[crossBrowser.docEl].scrollLeft; };
  crossBrowser.getScrollY = function() { return document[crossBrowser.docEl].scrollTop; };
}

crossBrowser.getPageWidth = function() { return document[crossBrowser.docEl].scrollWidth; };
crossBrowser.getPageHeight = function() { return document[crossBrowser.docEl].scrollHeight; };

crossBrowser.getMousePos = function(e) {
  e = e || window.event;
  var x = e.clientX + crossBrowser.getScrollX();
  var y = e.clientY + crossBrowser.getScrollY();
  if (crossBrowser.is_ie) { // absolute Mausposition für IE6/7 korrigieren
    var d = document[crossBrowser.docEl]; // d = HTML
    x = (x < d.clientLeft) ? 0 : x - d.clientLeft;
    y = (y < d.clientTop) ? 0 : y - d.clientTop;
  }
  return {x:x,y:y};
};

if (window.XMLHttpRequest) {
  crossBrowser.getXMLHttpRequest = function() { return new XMLHttpRequest(); };
} else if (window.ActiveXObject) {
  try {
    test = new ActiveXObject('Microsoft.XMLHTTP');
    crossBrowser.getXMLHttpRequest = function() { return new ActiveXObject('Microsoft.XMLHTTP'); };
  } catch (ex) {
    crossBrowser.getXMLHttpRequest = function() { return null; };
  }
  delete test;
} else {
  crossBrowser.getXMLHttpRequest = function() { return null; };
}

if (window.addEventListener) {
  crossBrowser.addEvent = function(el,eventType,eventFunction) {
    el.addEventListener(eventType,eventFunction,false);
  };
  crossBrowser.removeEvent = function(el,eventType,eventFunction) {
    el.removeEventListener(eventType,eventFunction,false);
  };
} else {
  crossBrowser.addEvent = function(el,eventType,eventFunction) {
    el.attachEvent('on'+eventType,eventFunction);
  };
  crossBrowser.removeEvent = function(el,eventType,eventFunction) {
    el.detachEvent('on'+eventType,eventFunction);
  };
}
if (crossBrowser.is_ie) {
  crossBrowser.avoidSelection = function() {
    document.selection.empty();
  };
} else {
  crossBrowser.avoidSelection = function() {
    window.getSelection().removeAllRanges();
  };
}


//Abkürzung für document.getElementById
function $(a) {
  return document.getElementById(a);
}

// DOM-Hilfsfunktionen
var domHelpers = {};
/* Fügt ein Element hinzu
 * parent: Das Elternelement, an dass das neue Element angehängt werden soll (Element)
 * tag: Was für ein Element es sein soll, 'text' erzeugt einen Text-Knoten (String)
 * attributes: Mögliche Atrribute für das neue Element, oder Text-Inhalt für Text-Knoten (Objekt,String)
 * childs: Mögliche Kinder Syntax: tag:{attributes:'',childs:{}} (Objekt)
 */
domHelpers.addElement = function(parent,tag,attributes,childs) {
  if (tag != 'text') {
    var newElement = document.createElement(tag);
    for (var a in attributes) {
      newElement.setAttribute(a,attributes[a]);
    }
  } else {
    var newElement = document.createTextNode(attributes);
  }
  for (var c in childs) {
    domHelpers.addElement(newElement,childs[c].tag,childs[c].attributes,childs[c].childs);
  }
  parent.appendChild(newElement);
};
/* Löscht ein Element
 * id: Die id des zu löschenden Elements (String)
 */
domHelpers.delElement = function(id) {
  if (!$(id) || !$(id).parentNode) {
    return;
  }
  $(id).parentNode.removeChild($(id));
};
/*
 * kompletten offsetLeft und offsetTop eines Elements
 */
/*
 * Funktionen registrieren die als onload ausgeführt werden.
 */
domHelpers.regFunctions = [];
domHelpers.addFunction = function(f) {
  domHelpers.regFunctions.push(f);
};
domHelpers.execute = function() {
  for (var i = 0; i < domHelpers.regFunctions.length; i++) {
    domHelpers.regFunctions[i]();
  }
};
//Ausführen aller Funktionen als onload
crossBrowser.addEvent(window,'load',domHelpers.execute);

//Objekt-Hilfsfunktionen
var objHelpers = {};
//Zentriert ein sichtbares Objekt auf dem Bildschirm
objHelpers.getCenterObj = function(p) {
  var pos = {l:0,t:0};
  var c = crossBrowser;
  var dim = {sX:c.getScrollX(),sY:c.getScrollY(),
             wX:c.getWindowInnerWidth(),wY:c.getWindowInnerHeight()};
  if (dim.wX > p.offsetWidth) {
    pos.l = Math.floor((dim.wX - p.offsetWidth) / 2 + dim.sX);
  }
  if (dim.wY > p.offsetHeight) {
    pos.t = Math.floor((dim.wY - p.offsetHeight) / 2 + dim.sY);
  }
  return pos;
};

objHelpers.getObjPos = function(obj) {
  var pos = {'l':0, 't':0};
  do {
    pos.l += obj.offsetLeft || 0;
    pos.t += obj.offsetTop || 0;
    obj = obj.offsetParent;
  } while (obj);
  return pos;
};


var php = {};

//TODO 
php.date = function(format, time) {
  var d = (time ? new Date(time*1000) : new Date());
  var z = function(s, digit) {
    s = s.toString();
    if (s.length < digit) {
      return new Array(++digit - s.length).join('0') + s;
    } else {
      return s;
    }
  };

  var f = {
    'a':null,
    'A':null,
    'B':null,
    'c':null,
    'd':function(){
      return z(f.j(), 2);
    },
    'D':null,
    'F':null,
    'g':function(){
      return d.getHours() % 12 || 12;
    },
    'G':function(){
      return d.getHours();
    },
    'h':function(){
      return z(f.g(), 2);
    },
    'H':function(){
      return z(f.G(), 2);
    },
    'i':function(){
      return z(d.getMinutes(), 2);
    },
    'I':null,
    'j':function(){
      return d.getDate();
    },
    'l':null,
    'L':null,
    'm':function(){
      return z(f.n(), 2);
    },
    'M':null,
    'n':function(){
      return d.getMonth() + 1;
    },
    'O':null,
    'r':null,
    's':function(){
      return z(d.getSeconds(), 2);
    },
    'S':null,
    't':null,
    'T':null,
    'U':null,
    'w':null,
    'W':null,
    'y':function(){
      return d.getFullYear().toString().slice(2);
    },
    'Y':function(){
      return d.getFullYear();
    },
    'z':null,
    'Z':null
  };

  return format.replace(/\\?([a-zA-Z])/g,function(p, b){
    if (p != b) {
      return b;
    } else if (f[b]) {
      return f[b]();
    } else {
      return b;
    }
  });
};

//TODO
php.sprintf = function() {
  if (arguments.length < 2) {
    return arguments[0] || '';
  }

  var rx = /%%|%(\d+\$)?s/g;
  var f = arguments[0];
  var args = arguments;
  var index = 0;

  var format = function(found, argIndex) {
    if (found == '%%') {
      return '%';
    }

    var val = argIndex ? args[argIndex.slice(0, -1)] : args[++index];

    return val.toString();
  };

  return f.replace(rx, format);
};


var drag = {};
drag.obj = null;
drag.functions = [];
drag.x = 0;
drag.y = 0;

drag.start = function(obj,functions) {
  drag.obj = obj;
  drag.x = mouse.x - parseInt(drag.obj.style.left,10);
  drag.y = mouse.y - parseInt(drag.obj.style.top,10);

  drag.functions = functions;
  for (var i = 0; i < drag.functions.length; i++) {
    crossBrowser.addEvent(drag.functions[i].element,drag.functions[i].type,drag.functions[i].func);
  }
  crossBrowser.addEvent(document,'mousemove',crossBrowser.avoidSelection);
};
drag.stop = function() {
  drag.obj = null;
  drag.x = 0;
  drag.y = 0;
  for (var i = 0; i < drag.functions.length; i++) {
    crossBrowser.removeEvent(drag.functions[i].element,drag.functions[i].type,drag.functions[i].func);
  }
  crossBrowser.removeEvent(document,'mousemove',crossBrowser.avoidSelection);
  drag.functions = [];
};

var changesize = {};
changesize.obj = null;
drag.functions = [];
changesize.x = 0;
changesize.y = 0;
changesize.direction = null;

changesize.start = function(obj,functions) {
  changesize.obj = obj.obj;
  changesize.direction = obj.direction;
  changesize.x = mouse.x - changesize.obj.offsetWidth;
  changesize.y = mouse.y - changesize.obj.offsetHeight;

  changesize.functions = functions;
  for (var i = 0; i < changesize.functions.length; i++) {
    crossBrowser.addEvent(changesize.functions[i].element,changesize.functions[i].type,changesize.functions[i].func);
  }
  crossBrowser.addEvent(document,'mousemove',crossBrowser.avoidSelection);
};
changesize.stop = function() {
  changesize.obj = null;
  changesize.direction = null;
  changesize.x = 0;
  changesize.y = 0;
  for (var i = 0; i < changesize.functions.length; i++) {
    crossBrowser.removeEvent(changesize.functions[i].element,changesize.functions[i].type,changesize.functions[i].func);
  }
  crossBrowser.removeEvent(document,'mousemove',crossBrowser.avoidSelection);
  changesize.functions = [];
};


function printShowImageLink(imageid,title) {
  return '/cartoons/'+encodeURIComponent(title)+'_'+imageid;
}
function printGalleryLink(t) {
  return '/'+t+'_gallery';
}
function printShopImageLink(imageid,title) {
  return '/shop/item/'+encodeURIComponent(title)+'_'+imageid;
}
function printShopGalleryLink(t) {
  return '/shop/selectedproducts';
}
function printToonagentLink(imageid,title) {
  return '/toonagent/showimage?imageid='+imageid;
}
function printToonagentGalleryLink(t) {
  return '/toonagent/gallery';
}
var rows = {};

rows.ROWINDEX = {'n':1, 'm':2, 's':2, 't':2, 'r':1, 'i':1, 'p':1, 'dm':1, 'd':2, 'shop':3, 'toonagent':3};
rows.NAVI = {'n':'search=Newest', 'm':'search=Most%20Viewed', 's':'search=Selected', 't':'search=Top%20Rated', 'r':'search=Random', 'i':'search=Illustrations', 'p':'search=Photo', 'dm':'search=Draw%20Me', 'd':'search=Most%20Discussed', 'shop':'', 'toonagent':''};
rows.REITER = {1:[['n','Newest','',printGalleryLink],['r','Random','',printGalleryLink],['i','Illustrations','',printGalleryLink],['dm','Draw%20Me','',printGalleryLink],['p','Photo','',printGalleryLink]],
               2:[['t','Top%20Rated','',printGalleryLink],['m','Most%20Viewed','',printGalleryLink],['d','Most%20Discussed','',printGalleryLink],['s','Selected','',printGalleryLink]],
               3:[['shop','','',printShopGalleryLink],['toonagent','','',printToonagentGalleryLink]]};

rows.index = {'n':0, 'm':0, 's':0, 't':0, 'r':0, 'i':0, 'p':0, 'dm':0, 'd':0, 'shop':0, 'toonagent':0};
rows.max = {'n':0, 'm':0, 's':0, 't':0, 'r':0, 'i':0, 'p':0, 'dm':0, 'd':0, 'shop':0, 'toonagent':0};
rows.func = {'n':printShowImageLink, 'm':printShowImageLink, 's':printShowImageLink, 't':printShowImageLink, 'r':printShowImageLink, 'i':printShowImageLink, 'p':printShowImageLink, 'dm':printShowImageLink, 'd':printShowImageLink, 'shop':printShopImageLink, 'toonagent':printToonagentLink},
rows.cartoons = {'n':[], 'm':[], 's':[], 't':[], 'r':[], 'i':[], 'p':[], 'dm':[], 'd':[], 'shop':[], 'toonagent':[]};
rows.row = {1:'', 2:'', 3:''};

rows.showRow = function(rowType, ind) {
  rows.index[rowType] += ind;
  if (rows.index[rowType] > rows.max[rowType]) {
    rows.index[rowType] -= ind;
    return;
  }
  if (rows.index[rowType] < 0) {
    rows.index[rowType] = 0;
  }
  if (rows.max[rowType] - rows.index[rowType] < 20 && !ajax.activeCall) {
    ajax.doRequest('/calls/indexAjax.php?load['+rowType+']=1&direction['+rowType+']=r&index['+rowType+']='+(rows.max[rowType]+1),false);
  }
  if (!rows.cartoons[rowType][rows.index[rowType]]) {
    rows.index[rowType] -= ind;
    ajax.doRequest('/calls/indexAjax.php?load['+rowType+']=1&direction['+rowType+']=l&print['+rowType+']=1&index['+rowType+']='+(rows.index[rowType]-1),true);
    return;
  }

  var dId = 'reiter'+rows.ROWINDEX[rowType]+'Content';
  var navi = rows.NAVI[rowType];
  rows.row[rows.ROWINDEX[rowType]] = 'load['+rowType+']=1_index['+rowType+']='+rows.index[rowType];

  var d = '';
  var t = rows.cartoons[rowType];
  for (var i = rows.index[rowType]; i < rows.index[rowType] + 15; i++) {
    if (t[i]) {
      d += printThumbShadow(t[i].h,t[i].w,t[i].imageid,t[i].userid,t[i].imageuid,t[i].title,t[i].artist,t[i].tags,t[i].last_commented,i+'_'+navi,rows.func[rowType]);
    }
  }
  $(dId).innerHTML = d;

  var Hash = "";
  Hash += "#"+rows.row[1];
  Hash += (Hash != "#") ? "_"+rows.row[2] : rows.row[2];
  Hash += (Hash != "#") ? "_"+rows.row[3] : rows.row[3];
  ajaxnavi.setHash(Hash);
};

function printThumbShadow(h,w,imageid,userid,imageuid,title,artist,tags,last_c,navi,func) {
  var mT = Math.floor((145 - h) / 2);
  var mB = 145 - h - mT;
  var mL = Math.floor((115 - w) / 2);
  var mR = 115 - w - mL;
  var commentImage = "";
  if (serverTime - last_c < 3600) {
    commentImage = "<div class=\"last_commented\"><img src=\"/misc/pics/icons/commenticon.gif\" title=\"Last commented within 1 hour\" alt=\"commentIcon\" /></div>";
  }
  return "<div class=\"thumb\" style=\"margin: "+mT+"px "+mR+"px "+mB+"px "+mL+"px;\"><div class=\"shadow_rt\"><div class=\"shadow_rb\" style=\"width:"+(w+5)+"px; height:"+(h+5)+"px;\"><div class=\"shadow_lb\" style=\"width:"+(w+5)+"px; height:"+(h+5)+"px;\"><a href=\""+func(imageid,title)+"\"><img title=\""+decodeURIComponent(title)+" (small)\" alt=\"Cartoon: "+decodeURIComponent(title)+" (small) by "+artist+" tagged "+tags+"\" onclick=\"setcookie('"+navi+"');\" src=\"/user/"+userid+"/thumbs/"+imageuid+".jpg\" /></a>"+commentImage+"</div></div></div></div>";
}

function toggleReiter(id,ind) {
  switchReiter(id,ind);
  $('reiter'+id+'Content').innerHTML = '<img src="/misc/pics/general/loading.gif" alt="loading" />';
  var what = rows.REITER[id][ind][0];
  ajax.doRequest('/calls/indexAjax.php?load['+what+']=1&print['+what+']=1&direction['+what+']=r',false);
}

function switchReiter(id,ind) {
  var anzD = rows.REITER[id].length;
  var inhalt = "";
  for (var i = 0; i < anzD - 1; i++) {
    if (i != ind) {
      inhalt += "<a href=\"\" onclick=\"javascript:void(toggleReiter('"+id+"',"+i+")); return false;\">"+unescape(rows.REITER[id][i][2])+"</a>";
    } else {
      inhalt += unescape(rows.REITER[id][i][2])+" [<a href=\""+rows.REITER[id][i][3](rows.REITER[id][i][1])+"\">"+reiterMore+"</a>]";
    }
    inhalt += ' | ';
  }
  if (ind != i) {
    inhalt += "<a href=\"\" onclick=\"javascript:void(toggleReiter('"+id+"',"+i+")); return false;\">"+unescape(rows.REITER[id][i][2])+"</a>";
  } else {
    inhalt += unescape(rows.REITER[id][i][2])+" [<a href=\""+rows.REITER[id][i][3](rows.REITER[id][i][1])+"\">"+reiterMore+"</a>]";
  }
  $('reiter'+id).innerHTML = inhalt;
  $('reiter'+id+"R").onclick = new Function("rows.showRow('"+rows.REITER[id][ind][0]+"',5); return false;");
  $('reiter'+id+"L").onclick = new Function("rows.showRow('"+rows.REITER[id][ind][0]+"',-5); return false;");
}

//Globaler Mousemove Handler, hält die Mausposition vorrätig.
var mouse = {};
mouse.x = 0;
mouse.y = 0;
mouse.move = function(e) {
  var mp = crossBrowser.getMousePos(e);
  mouse.x = mp.x;
  mouse.y = mp.y;
};
crossBrowser.addEvent(document,'mousemove',mouse.move);

//Rating-Info
//Zeigt ne Kurz-Info fürs Rating an.
function ratingInfo(state,rate) {
  var p = $('rating_info');
  if (state) {
    switch (rate) {
      case 1:
        p.innerHTML = "Poor";
        break;

      case 2:
        p.innerHTML = "Uhm...";
        break;

      case 3:
        p.innerHTML = "Good";
        break;

      case 4:
        p.innerHTML = "Superb";
        break;

      case 5:
        p.innerHTML = "Hilarious!";
        break;

      default:
        p.innerHTML = "login to rate";
        break;
    }
  } else {
    p.innerHTML = "&nbsp;";
  }
}

function toggleE(id) {
	var p = $(id);
	if (p.style.display == 'none') {
		p.style.display = '';
	} else {
		p.style.display = 'none';
	}
}

function markAll(checkboxes) {
  var anzahlC = document.pnForm.elements.length;
  for (var i = 0; i < anzahlC; i++) {
    document.pnForm.elements[i].checked = true;
  }
}

function toggle_all_check(f,test) {
  var anzahlI = f[test].length;
  for (var i = 0; i < anzahlI; i++) {
    if (f[test][i].checked) {
      f[test][i].checked = false;
    } else {
      f[test][i].checked = true;
    }
  }
}

var showInfo = {};
showInfo.over = function(user) {
  if (!$('Info')) {
    domHelpers.addElement(document.body,'div',{'id':'Info','style':'border: 1px dashed #46415C; display:none; position:absolute; top:0px; left:0px; background-color:#ffffff; padding:3px 5px 3px 5px; color:#494949;'},{});
  }
  $('Info').innerHTML = "<b>"+user+"</b>";
  $('Info').style.display = '';
  crossBrowser.addEvent(document,'mousemove',showInfo.move);
};
showInfo.out = function() {
  domHelpers.delElement('Info');
  crossBrowser.addEvent(document,'mousemove',showInfo.move);
};
showInfo.move = function(e) {
  if ($('Info') != null) {
    $('Info').style.left = (mouse.x + 15) + "px";
    $('Info').style.top	= (mouse.y + 15) + "px";
  }
};

function setcookie(navi) {
	var daten = document.cookie;
	var navid = '';
	var suche = /toonpool_navi=navid%3D(\d+)%2C/;
	if (suche.exec(daten) != null) {
		navid = 'navid%3D'+RegExp.$1+'%2C';
	}
	var now = new Date();
	var ms = now.getTime();
	ms += serverTime + 365 * 24 * 60 * 60 * 1000;
	now.setTime(ms);
	var l = window.location.href;
	var p = l.split('/');
	var d = p[2].split('.');
	var domain = '';
	for (var i = d.length - 1; i > 0; i--) {
	  domain = '.'+d[i]+domain;
	}
  document.cookie = "toonpool_navi="+navid+encodeURIComponent(navi)+";path=/;expires="+now.toGMTString()+";domain="+domain;//;domain=.pohlenzcartoons.de
}

function setDcookie() {
  var now = new Date();
  now.setTime((now.getTime + 90 * 24 * 60 * 60 * 1000));
  document.cookie = 'postcardshop='+encodeURIComponent(window.location.href)+';path=/;expires='+now.toGMTString();
}

function showCotd(data) {
  if (data == 'block') {
    $('layer_0').style.display = 'block';
    var xy = objHelpers.getCenterObj($('layer_0'));
		document.getElementById('layer_0').style.left = xy.l+"px";
    document.getElementById('layer_0').style.top = xy.t+"px";
  } else if (data == 'block9') {
    $('layer_9').style.display = 'block';
    var xy = objHelpers.getCenterObj($('layer_9'));
		document.getElementById('layer_9').style.left = xy.l+"px";
    document.getElementById('layer_9').style.top = xy.t+"px";
  }
}

function checkEmail(email) {
  var suche = /[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,4}/i;
  if (suche.exec(email) != null) {
    return true;
  } else {
    return false;
  }
}


function changeSelect(id,sel,val) {
  if (val == 0) {
    return;
  }
  var f = $(id);
  var anzS = f[sel].options.length;
  for (var i = 0; i < anzS; i++) {
    if (f[sel].options[i].value == val) {
      f[sel].options[i].selected = true;
      break;
    }
  }
}

function check_js_cookie(dir) {
  var cookiename = 'toonpool_'+dir;
  var coo = document.cookie;
  if (coo.indexOf(cookiename) != -1) {
    var p = $('header_tb_top');
    var c = $('js_cookie_warning');
    p.removeChild(c);
  }
}

var layer = {};
layer.create = function(id,styles,closeAction,properties,html) {
  if ($(id)) {
    domHelpers.delElement(id);
  }
  opacitylayer.create();
  domHelpers.addElement($('layer_holder'),'div',{'id':id,'style':styles},{});
  if (properties != null && typeof properties.tpClassName == 'string') {
    $(id).className = properties.tpClassName;
  } else {
    $(id).className = 'layer';
  }

  var d = '';
  d += "<div class='page_rt'><div class='page_lt'><div class='page_rb'><div class='page_lb'><div class='content'>";
  d += "<div style='width:100%;height:100%;' id='"+id+"_content'>";
  if (html) {
    d += html;
  }
  d += "</div>";
  d += "<div class='close'><a class='a_img' href=\"javascript:void(layer.close('"+id+"'));"+closeAction+"\"><img src=\"/misc/pics/round/x.gif\" alt=\"[X]\" /></a></div>";
  d += "<div class='dragger' onmousedown=\"layer.down('"+id+"');\">&nbsp;</div>";
  d += "</div></div></div></div></div>";

  $(id).innerHTML = d;
};
layer.down = function(id) {
  drag.start($(id),
             [{'element':document,'type':'mouseup','func':drag.stop},
              {'element':document,'type':'mousemove','func':layer.move}]);
};
layer.show = function(id) {
  if ($(id)) {
    $(id).style.display = 'block';
    var xy = objHelpers.getCenterObj($(id));
    $(id).style.left = xy.l+"px";
    $(id).style.top = xy.t+"px";
  }
};
layer.move = function() {
  drag.obj.style.left = (mouse.x - drag.x) + "px";
  drag.obj.style.top  = (mouse.y - drag.y) + "px";
};
layer.close = function(id) {
  domHelpers.delElement(id);
  domHelpers.delElement('opacity');
};
opacitylayer = {};
opacitylayer.create = function() {
  domHelpers.delElement('opacity');
  domHelpers.addElement($('layer_holder'),'div',{'id':'opacity'},[]);
  $('opacity').style.zIndex = 8000;
  $('opacity').style.position = 'absolute';
  $('opacity').style.height = crossBrowser.getPageHeight() + 'px';
  $('opacity').style.width = '100%';
  $('opacity').style.top = '0px';
  $('opacity').style.left = '0px';
  $('opacity').style.backgroundColor = 'black';
  $('opacity').style.opacity = 0.75;
  if (crossBrowser.is_ie) {
    $('opacity').style.filter = 'alpha(opacity=75)';
  }
};

var choose = {};
/*choose.choose = function(html,buttons) {
  var d = html;
  d += "<br />";
  for (var b in buttons) {
    d += '<a href="'+buttons[b]['href']+'"><input type="button" value="'+buttons[b]['value']+'" /></a>';
  }
  var lD = {};
  lD['id'] = 'c_'+(new Date()).getTime();
  lD['styles'] = '';
  lD['closeAction'] = '';
  lD['properties'] = null;
  choose.layer(d,lD);
};*/

choose.layer = function(html,layerData) {
  layer.create(layerData['id'],layerData['styles'],layerData['closeAction'],layerData['properties'], html);
  layer.show(layerData['id'])
};

choose.shop = {};
choose.shop.show = function(lStrings, products) {
  var loc = window.location.search;
  var locSearch = /p=(\d+)/;
  var p = '';
  if (locSearch.exec(loc) != null) {
    p = '?p=' + RegExp.$1;
  }
  var s;
  var lD = {};
  lD['id'] = 'c_'+(new Date()).getTime();
  lD['styles'] = '';
  lD['closeAction'] = '';
  lD['properties'] = null;

  var d = '<div>';
  d += '<img src="/misc/pics/shop/check_big.gif" alt="checkmark" style="float: left; margin: 0px 10px 0px -15px;" />';
  d += '<h2>'+lStrings['headline']+'</h2><br /><br />';
  for (var productid in products) {
    s = products[productid];
    d += '<span style="white-space: nowrap;">»'+s['title']+'«, '+s['desc']+(s['format'] != '' ? ' ('+s['format']+')' : '')+(s['details'] ? ' ('+s['details'].join(', ')+')' : '')+'</span><br />';
  }
  d += '<br />';
  d += '<b>'+lStrings['question']+'</b><br /><br /><br />';
  d += '<input type="button" value="'+lStrings['continue']+'" onclick="layer.close(\''+lD['id']+'\');" style="float: right;" />';
  d += '<input type="button" value="'+lStrings['finish']+'" onclick="window.location.href = \'/shop/cart'+p+'\';" style="float: right;" /><br /><br />';
  d += '</div>';

  choose.layer(d,lD); 
};

var tpgen = {};

tpgen.printNavi = function(countAll, countOnPage, actualPage, link1, link2, options) {
  link2 = link2 || '';
  options = options || {};

  options.specialPages = options.specialPages || {};

  var separator = link1.indexOf('?') != -1 ? '&' : '?';
  var countPages = Math.ceil(countAll / countOnPage);
  //Only 1 Page? Return a whitespace
  if (countPages == 1) {
      return '&nbsp;';
  }

  var start = 1;
  var stop = countPages;

  var naviPart1 = 'Page ';
  var naviPart2 = '';
  var i;

  if (countPages > 5) {
    i = actualPage - 1;
    naviPart1 += '&nbsp;<a href="'+(options['specialPages'][i] == null ? link1+separator+'page='+i+link2 : options['specialPages'][i])+'" class="a_img"'+(actualPage > 1 ? '' : ' style="visibility: hidden;"')+'><img alt="left" src="/misc/pics/round/bub_left.gif" /></a>';
    naviPart1 += '&nbsp;<a href="'+(options['specialPages'][1] == null ? link1+separator+'page=1'+link2 : options['specialPages'][1])+'" class="a_deco"'+(actualPage > 3 ? '' : ' style="visibility: hidden;"')+'>First</a>';

    if (actualPage > 3) {
        start = actualPage - 2;
        if (countPages - actualPage > 2) {
            stop = actualPage + 2;
        } else {
            start = countPages - 4;
        }
    } else {
        stop = 5;
    }

    naviPart2 += '&nbsp;<a href="'+(options['specialPages'][countPages] == null ? link1+separator+'page='+countPages+link2 : options['specialPages'][countPages])+'" class="a_deco"'+(actualPage + 2 < countPages ? '' : ' style="visibility: hidden;"')+'>Last</a>';
    i = actualPage + 1;
    naviPart2 += '&nbsp;<a href="'+(options['specialPages'][i] == null ? link1+separator+'page='+i+link2 : options['specialPages'][i])+'" class="a_img"'+(actualPage < countPages ? '' : ' style="visibility: hidden;"')+'><img alt="right" src="/misc/pics/round/bub_right.gif" /></a>';
  }

  for (i = start; i <= stop; i++) {
    if (i != actualPage) {
      naviPart1 += '&nbsp;<a href="'+(options.specialPages[i] != null ? options.specialPages[i] : link1+separator+'page='+i+link2)+'" class="a_deco">'+i+'</a>';
    } else {
      naviPart1 += '&nbsp;<span class="gal_thispage">'+i+'</span>';
    }
  }

  return naviPart1+naviPart2;
};


var ajax = {};
ajax.debug = false;
ajax.activeCall = false;
ajax.req = null;
ajax.doRequest = function(url,loadingAni) {
  if (loadingAni) {
    ajax.setLoadingAni(true);
  }

  var data = '';
  if (url.indexOf('?') != -1) {
    data = url.split('?')[1];
    url = url.split('?')[0];
  }

  ajax.req = crossBrowser.getXMLHttpRequest();
  if (!ajax.req) {
    alert('Unfortunatelly you browser doesn\'t support this feature.');
    return false;
  }
  ajax.activeCall = true;

  ajax.req.onreadystatechange = function() {
    if (ajax.req.readyState == 4) {
      if (ajax.req.status == 200) {
        if (ajax.debug) {
          alert(ajax.req.responseText);
        }
        if (ajax.req.getResponseHeader('Content-Type').indexOf('text/xml') != -1) {
          if (ajax.debug) {alert('xml')}
          try {
            ajax.processResponseXML(ajax.req.responseXML.documentElement);
          } catch (ex) {
            alert('Sorry: XML-Error...');
          }
        } else if (ajax.req.getResponseHeader('Content-Type').indexOf('text/javascript') != -1) {
          if (ajax.debug) {alert('js')}
          try {
            eval(ajax.req.responseText);
          } catch (ex) {
            alert("Invalid javascript:\n"+ex.number+"\n"+ex.message+"\n"+ajax.req.responseText);
          }
        } else {
          if (ajax.debug) {
            alert(ajax.req.getResponseHeader('Content-Type'));
          }
        }
      } else {
        //alert(ajax.req.status);
      }
      ajax.setLoadingAni(false);
      ajax.activeCall = false;
      ajax.req = null;
    }
  };

  ajax.req.open('POST', url, true);
  ajax.req.setRequestHeader('Method', 'POST '+url+' HTTP/1.1');
  ajax.req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  ajax.req.setRequestHeader('101010_2_42', (new Date()).getTime());
  ajax.req.send(data);
};
ajax.abort = function() {
  if (ajax.req) {
    ajax.req.abort();
  }
};
ajax.setLoadingAni = function(state) {
  if (!$('ajaxLoadingMsg')) {
    domHelpers.addElement(window.document.body,'div',{'id':'ajaxLoadingMsg','style':"width:105px; height:150px; position:absolute; top:0px; left:0px; z-index:10000; display:none; background-color:#D8D9E5; border:2px solid #46415C;"},[{'tag':'img','attributes':{'src':'/misc/pics/general/loading.gif','alt':'loading'},'childs':{}}]);
  }
  var p = $('ajaxLoadingMsg');
  if (state) {
    p.style.display = '';
    var lt = objHelpers.getCenterObj(p);
    p.style.left = lt.l+'px';
    p.style.top = lt.t+'px';
  } else {
    p.style.display = 'none';
  }
};
ajax.getFormData = function(id) {
  var p = $(id);
  if (!p) {
    return '';
  }

  var params = '';
  for (var anzE = p.elements.length, i = 0; i < anzE; i++) {
    if (((p.elements[i].type == 'checkbox' || p.elements[i].type == 'radio') && p.elements[i].checked === false) || !p.elements[i].name) {
      continue;
    }

    if (p.elements[i].multiple === true) {
      for (var anzO = p.elements[i].options.length, j = 0; j < anzO; j++) {
        if (p.elements[i].options[j].selected === true) {
          params += '&'+p.elements[i].name+'='+encodeURIComponent(p.elements[i].options[j].value);
        }
      }
      continue;
    }

    params += '&'+p.elements[i].name+'='+encodeURIComponent(p.elements[i].value);
  }
  return params;
};
ajax.getArrayData = function(array,arrayName) {
  var params = '';
  for (var i in array) {
    if (typeof array[i] == 'object') {
      params += ajax.getArrayData(array[i],arrayName+'['+i+']');
    } else {
      params += '&'+arrayName+'['+i+']='+encodeURIComponent(array[i]);
    }
  }
  return params;
};
ajax.processResponseXML = function(xmlR) {
  try {
    for (var anzN = xmlR.childNodes.length, i = 0; i < anzN; i++) {
      if (xmlR.childNodes[i].nodeName == 'sourcetext') {
        if (ajax.debug) {alert('source, Fallback needed')}
        return false;
      }
      if (xmlR.childNodes[i].nodeName == 'response') {
        var INode = xmlR.childNodes[i];

        switch (INode.getAttribute('type')) {
        case 'javascript':
          for (var anzC = INode.childNodes.length, j = 0; j < anzC; j++) {
            if (INode.childNodes[j].nodeName == 'object') {
              try {
                eval(INode.childNodes[j].firstChild.nodeValue);
              } catch(exx) {
                alert("Invalid javascript:\n"+exx.number+"\n"+exx.message+"\n"+INode.childNodes[j].firstChild.nodeValue);
              }
            }
          }
          break;

        case 'html':
          for (var anzC = INode.childNodes.length, j = 0; j < anzC; j++) {
            if (INode.childNodes[j].nodeName == 'object') {
              try {
                var disposition = INode.childNodes[j].getAttribute('disposition');
                $(disposition).innerHTML = INode.childNodes[j].firstChild.nodeValue;
              } catch(exx) {
                alert("Invalid content:\n"+exx.message+"\n"+INode.childNodes[j].firstChild.nodeValue);
              }
            }
          }
          break;

        default:
          alert("Unknown:"+INode.getAttribute('type'));
          break;
        }
      }
    }
  } catch(ex) {
    if (ajax.debug) {alert(ex)}
    return false;
  }
  return true;
};

var ajaxnavi = {};
ajaxnavi.timer = null;
ajaxnavi.actualHash = '';
ajaxnavi.init = function() {
  ajaxnavi.load();
};
ajaxnavi.load = function() {
  if (crossBrowser.is_ie) {
    var newHash = decodeURIComponent(window.frames['ajaxIeNavi'].window.location.search.substring(1));
    if (window.location.hash.replace('#','') != newHash) {
      window.location.hash = newHash;
    }
  } else {
    var newHash = window.location.hash;
  }

  if (newHash == ajaxnavi.actualHash) {
    ajaxnavi.timer = window.setTimeout(ajaxnavi.load,500);
    return;
  }

  ajaxnavi.actualHash = newHash;
  newHash = newHash.replace('#','');

  if (window.location.href.indexOf('/cartoons/') != -1) {//showImage
    try {
      if (newHash != '' && newHash != 'top') {
        eval(newHash+'.show();');
      } else if ($('layer_0')) {
        domHelpers.delElement('layer_0');
        domHelpers.delElement('opacity');
      }
    } catch (ex) {
    }
  } else {
    if (newHash != '' && newHash != 'top') {
      var data = newHash.split('_');
      var query = '';
      var search = /\[(.{1,2})\]/;
      if (data[0]) {
        if (search.exec(data[0]) != null) {
          query += data[0]+'&'+data[1]+'&direction['+RegExp.$1+']=lr&print['+RegExp.$1+']=1';
        }
      }
      if (data[2]) {
        if (search.exec(data[2]) != null) {
          query += (query != '') ? '&'+data[2]+'&'+data[3] : data[2]+'&'+data[3];
          query += '&direction['+RegExp.$1+']=lr&print['+RegExp.$1+']=1';
        }
      }
      if (query != '') {
        ajax.doRequest('/calls/indexAjax.php?'+query,true);
      }
    }
  }

  if (!crossBrowser.is_ie) {
    ajaxnavi.timer = window.setTimeout(ajaxnavi.load,500);
  }
};
ajaxnavi.setHash = function(hash) {
  clearTimeout(ajaxnavi.timer);
  if (hash == '#') {
    domHelpers.delElement('opacity');
  }
  if (crossBrowser.is_ie) {
    ajaxnavi.actualHash = hash.replace('#','');
    window.frames['ajaxIeNavi'].window.location.search = '?'+encodeURIComponent(ajaxnavi.actualHash);
    window.location.hash = ajaxnavi.actualHash;
  } else {
    ajaxnavi.actualHash = hash;
    if (!crossBrowser.is_safari) {
      window.location.hash = hash;
    } else {
      window.location.hash = hash.replace('#','');
    }
    ajaxnavi.timer = window.setTimeout(ajaxnavi.load,500);
  }
};


var suggest = {};
suggest.s = {};
suggest.sPointer = null;

suggest.cachedQuestion = false;//Falls jemand zu schnell tippert
suggest.lastQuery = '';
suggest.lastSugg = [];
suggest.actualRow = 0;
suggest.mouseclick = false;//Blur und Mausklick abfangen siehe mousedown und mouseup functions
suggest.operaTimer = null;

suggest.addSuggestion = function(sourceid,target,execute,onsubmit) {
  if (!$(sourceid)) {
    return null;
  }
  suggest.s[sourceid] = {};
  var p = suggest.s[sourceid];

  p.sourceid = sourceid;
  p.source = $(sourceid);//Hier kommen die Daten her
  p.sourceDefaultValue = p.source.value;
  p.target = target;//Aufruffunktion für das abholen der Daten
  p.execute = execute;//Diese Funktion wird beim wählen eines Vorschlages ausgeführt
  p.onsubmit = onsubmit;

  p.source.setAttribute('autocomplete','off');

  crossBrowser.addEvent(p.source,'focus',suggest.focus);
};

suggest.focus = function(e) {
  var el = crossBrowser.is_ie ? window.event.srcElement : this;
  var p = suggest.sPointer = suggest.s[el.id];

  if (p.source.value == p.sourceDefaultValue) {
    p.source.value = '';
  }

  crossBrowser.addEvent(p.source.form,'submit',p.onsubmit);
  if (!crossBrowser.is_opera) {
    crossBrowser.addEvent(p.source,'blur',suggest.clear);
  } else {
    crossBrowser.addEvent(p.source,'blur',function(){suggest.operaTimer = window.setTimeout(suggest.clear,0);});
  }
  crossBrowser.addEvent(p.source,'keyup',suggest.ask);
  crossBrowser.addEvent(window.document,'unload',ajax.abort);
  crossBrowser.addEvent(window.document,'mousedown',suggest.mousedown);
  crossBrowser.addEvent(window.document,'mouseup',suggest.mouseup);
  //crossBrowser.addEvent(window.document,'contextmenu',suggest.contextmenu);
  crossBrowser.addEvent(window.document,'keydown',suggest.keydown);
  if (!$(p.sourceid+'_response_div')) {
    p.divid = p.sourceid+'_response_div';
    domHelpers.addElement(window.document.body,'div',{'id':p.divid,'class':'suggest_response_div'},[]);
    if (crossBrowser.is_ie) {//IE sucks
      $(p.divid).className = 'suggest_response_div';
    }
    var pos = objHelpers.getObjPos(p.source);
    pos.w = p.source.offsetWidth;
    pos.t += p.source.offsetHeight;
    $(p.divid).style.width = (pos.w - 4)+'px';//2x2=4 für border
    $(p.divid).style.top = pos.t+'px';
    $(p.divid).style.left = pos.l+'px';
  }
};

suggest.clear = function(e) {
  e = e || window.event;
  var p = suggest.sPointer;

  if (suggest.mouseclick) {
    p.source.focus();
    return;
  }
  var temp = p.source;

  domHelpers.delElement(p.divid);
  crossBrowser.removeEvent(window.document,'keydown',suggest.keydown);
  //crossBrowser.removeEvent(window.document,'contextmenu',suggest.contextmenu);
  crossBrowser.removeEvent(window.document,'mouseup',suggest.mouseup);
  crossBrowser.removeEvent(window.document,'mousedown',suggest.mousedown);
  crossBrowser.removeEvent(window.document,'unload',ajax.abort);
  crossBrowser.removeEvent(p.source,'keyup',suggest.ask);
  if (!crossBrowser.is_opera) {
    crossBrowser.removeEvent(p.source,'blur',suggest.clear);
  } else {
    crossBrowser.removeEvent(p.source,'blur',function(){suggest.operaTimer = window.setTimeout(suggest.clear,0);});
  }
  crossBrowser.removeEvent(p.source.form,'submit',p.onsubmit);

  suggest.sPointer = null;
  temp.blur();
};

suggest.ask = function(e) {
  var p = suggest.sPointer;

  e = e || window.event;
  if (typeof e != 'undefined' && e != null) {//IEe sucks window.event == null omg
    switch (e.keyCode) {//prevent searching while selecting a search result
    case 40://Down
    case 38://Up
    case 27://Esc
      return;
      break;
    }
  }

  if (!ajax.activeCall) {
    suggest.cachedQuestion = false;
    p.target();
  } else {
    suggest.cachedQuestion = true;
  }
};

suggest.processResponse = function(sugg) {
  var p = suggest.sPointer;

  //Original-value ans Array pappen
  sugg.unshift({'result':p.source.value,'hidden':'0','count':'0'});
  suggest.lastSugg = sugg;

  if (sugg.length > 1) {
    var d = '';
    d += "<table class='suggest_response_table'>";
    for (var i = 1; i < sugg.length; i++) {
      d += "<tr id='"+p.sourceid+"_response_tr_"+i+"' class='suggest_response_tr_normal' onmouseover=\"suggest.changeSelect("+i+");\">";
      d += "<td style='text-align:left; padding:1px;'>"+sugg[i].result+"</td>";
      d += "<td style='text-align:right; padding:1px;'>"+sugg[i].count+"</td>";
      d += "</tr>";
    }
    d += "</table>";
    $(p.divid).innerHTML = d;
    $(p.divid).style.display = 'block';
  } else {
    $(p.divid).innerHTML = '';
    $(p.divid).style.display = 'none';
  }
  if (suggest.cachedQuestion) {
    suggest.ask();
  }
};

suggest.changeSelect = function(index) {
  var p = suggest.sPointer;

  if ($(p.divid).style.display == 'none' && suggest.lastSugg.length > 1) {
    $(p.divid).style.display = 'block';
  }
  if ($(p.divid).style.display == 'none') {
    return;
  }
  suggest.actualRow = index;
  for (var i = 1; i < suggest.lastSugg.length; i++) {
    $(p.sourceid+'_response_tr_'+i).className = ((index != i) ? 'suggest_response_tr_normal' : 'suggest_response_tr_selected');
  }
};

suggest.checkMouseClick = function(e) {
  var p = suggest.sPointer;

  e = e || event;
  var mp = crossBrowser.getMousePos(e);
  var dim = objHelpers.getObjPos($(p.divid));
  dim.t += 2;
  dim.l += 2;
  dim.b = dim.t + $(p.divid).offsetHeight - 5;
  dim.r = dim.l + $(p.divid).offsetWidth - 5;
  if (dim.l <= mp.x && dim.r >= mp.x && dim.t <= mp.y && dim.b >= mp.y) {
    return true;
  } else {
    return false;
  }
}

suggest.mousedown = function(e) {
  var p = suggest.sPointer;

  if (!suggest.checkMouseClick(e)) {
    return false;
  }
  suggest.mouseclick = true;
  p.source.focus();
  return false;
};

suggest.mouseup = function(e) {
  var p = suggest.sPointer;
  if (!p) {
    return;
  }

  suggest.mouseclick = false;
  if (suggest.checkMouseClick(e)) {
    p.execute();
    return;
  }
  p.source.focus();
};

/*suggest.contextmenu = function(e) {
  var p = suggest.sPointer;

  suggest.mouseclick = true;
  if (suggest.checkMouseClick(e)) {
    p.source.focus();
    return false;
  }
  return true;
};*/

suggest.keydown = function(e) {
  var p = suggest.sPointer;

  e = e || window.event;
  switch (e.keyCode) {
  case 40://Down
    if (suggest.lastSugg.length > 0) {
      var index = (suggest.actualRow + 1 < suggest.lastSugg.length) ? suggest.actualRow + 1 : 0;
      p.execute(index);
      suggest.changeSelect(index);
    }
    break;
  case 38://Up
    if (suggest.lastSugg.length > 0) {
      var index = (suggest.actualRow - 1 > -1) ? suggest.actualRow - 1 : suggest.lastSugg.length - 1;
      p.execute(index);
      suggest.changeSelect(index);
    }
    break;
  case 27://Esc
    suggest.actualRow = 0;
    $(p.divid).style.display = 'none';
    break;
  }
};

//Example target-functions
suggest.tagTarget = function () {
  var p = suggest.sPointer;

  var pos;
  var search = p.source.value;
  if (search == suggest.lastQuery) {
    return;
  }
  suggest.lastQuery = search;
  if ((pos = search.lastIndexOf(' ')) != -1) {
    search = search.substr(pos+1);
  }
  ajax.doRequest('/calls/searchTagAjax.php?search='+encodeURIComponent(search)+'&max=10&callback=suggest.processResponse',false);
};

suggest.artistTarget = function() {
  var p = suggest.sPointer;

  var search = p.source.value;
  if (search == suggest.lastQuery) {
    return;
  }
  suggest.lastQuery = search;
  ajax.doRequest('/calls/searchArtistAjax.php?search='+encodeURIComponent(search)+'&max=10&artist=1&callback=suggest.processResponse',false);
};

suggest.mailTarget = function() {
  var p = suggest.sPointer;

  var search = p.source.value;
  if (search == suggest.lastQuery) {
    return;
  }
  suggest.lastQuery = search;
  ajax.doRequest('/calls/searchArtistAjax.php?search='+encodeURIComponent(search)+'&max=10&callback=suggest.processResponse',false);
};

//Example execute-functions
suggest.tagExecute = function(index) {
  var p = suggest.sPointer;

  var clear = true;
  var ind = suggest.actualRow;
  if (typeof index != 'undefined') {
    clear = false;
    ind = index;
  }
  p.source.value = suggest.lastSugg[ind].result;
  if (clear) {
    p.onsubmit();
  }
};

suggest.artistExecute = function(index) {
  var p = suggest.sPointer;

  var clear = true;
  var ind = suggest.actualRow;
  if (typeof index != 'undefined') {
    clear = false;
    ind = index;
  }
  p.source.value = suggest.lastSugg[ind].result;
  $(p.sourceid+'_hidden').value = suggest.lastSugg[ind].hidden;
  if (clear) {
    suggest.clear();
  }
};

suggest.mailExecute = function(index) {
  var p = suggest.sPointer;

  var clear = true;
  var ind = suggest.actualRow;
  if (typeof index != 'undefined') {
    clear = false;
    ind = index;
  }
  p.source.value = suggest.lastSugg[ind].result;
  if (clear) {
    suggest.clear();
  }
};

//Example onsubmit-functions
suggest.tagOnsubmit = function() {
  var p = suggest.sPointer;
  var f = p.source.form;
  suggest.clear();

  f.submit();
  return false;
};

suggest.artistOnsubmit = function() {
  var p = suggest.sPointer;

  $(p.divid).style.display = 'none';
  //Damit nicht nochmal gesucht wird, und man nachher wieder an der richtigen Stelle ist.
  suggest.lastQuery = p.source.value;
  suggest.actualRow = 0;
  return false;
};

suggest.mailOnsubmit = function() {
  var p = suggest.sPointer;

  $(p.divid).style.display = 'none';
  //Damit nicht nochmal gesucht wird, und man nachher wieder an der richtigen Stelle ist.
  suggest.lastQuery = p.source.value;
  suggest.actualRow = 0;
  return false;
};

domHelpers.addFunction(function(){suggest.addSuggestion('gadgetUserSearchInput',suggest.artistTarget,suggest.artistExecute,suggest.artistOnsubmit);});
domHelpers.addFunction(function(){suggest.addSuggestion('search_qi',suggest.tagTarget,suggest.tagExecute,suggest.tagOnsubmit);});
domHelpers.addFunction(function(){suggest.addSuggestion('artist_mail_search',suggest.mailTarget,suggest.mailExecute,suggest.mailOnsubmit);});


var changelang = {};

changelang.show = function(el) {
  var pos = objHelpers.getObjPos(el);
  $('changeLangSelect').style.top = (pos.t + 25) + 'px';
  $('changeLangSelect').style.left = (el.offsetLeft - 70) + 'px';
  $('changeLangSelect').style.display = 'block';
};

changelang.hide = function() {
  $('changeLangSelect').style.display = 'none';
};


var stb = {};
stb.iconDirectory='/misc/pics/socialbookmarking/';

stb.addButton = function(iconID, iconInactive, iconActive, name, url) {
	document.write('<span id="sButton-' + iconInactive + '"><a class="a_img" ref="nofollow" href="' + url + '" title="Bookmark at ' + name +'" target="_blank"><img src="' + stb.iconDirectory + '/' + iconInactive + '" id="' + iconID + '" onmouseover="stb.iconSwap(\'' + iconID + '\',\'' + iconActive + '\')" onmouseout="stb.iconSwap(\'' + iconID + '\',\'' + iconInactive + '\')" style="vertical-align:middle;" /></a></span> ');
};

stb.iconSwap = function (iconID, iconName){
	var icon = document.getElementById(iconID);
	icon.src = stb.iconDirectory + iconName;
};

stb.show = function() {
	var url = encodeURIComponent(document.URL);
	var title = encodeURIComponent(document.title);
	stb.addButton('misterwong', 'misterwong-grey.gif', 'misterwong.gif', 'Mister Wong', 'http://www.mister-wong.de/index.php?action=addurl&bm_url=' + url + '&amp;bm_description=' + title);
	stb.addButton('yigg', 'yigg-grey.gif', 'yigg.gif', 'YiGG.de', 'http://www.yigg.de/neu?exturl=' + url);
	stb.addButton('google', 'google-grey.gif', 'google.gif', 'Google', 'http://www.google.com/bookmarks/mark?op=add&amp;hl=de&amp;bkmk=' + url + '&amp;title=' + title);
	stb.addButton('webnews', 'webnews-grey.gif', 'webnews.gif', 'Webnews', 'http://www.webnews.de/einstellen?url=' + url + '&amp;title=' + title);
	stb.addButton('linkarena', 'linkarena-grey.gif', 'linkarena.gif', 'LinkARENA', 'http://linkarena.com/bookmarks/addlink/?url=' + url + '&amp;title=' + title);
	stb.addButton('delicious', 'delicious-grey.gif', 'delicious.gif', 'del.icio.us', 'http://del.icio.us/post?url=' + url + '&amp;title=' + title);
	stb.addButton('digg', 'digg.gif', 'digg.gif', 'Digg', 'http://digg.com/submit?phase=2&amp;url=' + url + '&amp;title=' + title);
	stb.addButton('yahoo', 'yahoo-grey.gif', 'yahoo.gif', 'Yahoo! My Web', 'http://myweb2.search.yahoo.com/myresults/bookmarklet?u=' + url + '&amp;t=' + title);
};



function writeSearchPlugin() {
  if ((typeof window.external == 'object') && ((typeof window.external.AddSearchProvider == 'unknown') || (typeof window.external.AddSearchProvider == 'function'))) {
    document.write('<a href="javascript:window.external.AddSearchProvider(\'http://www.toonpool.com/misc/plugins/toonpoolcom.xml\');">Add a <strong>toonpool.com</strong> searchpanel to your browser.</a>');
  } else if ((typeof window.sidebar == "object") && (typeof window.sidebar.addSearchEngine == "function")) {
    document.write('<a href="javascript:window.sidebar.addSearchEngine(\'http://www.toonpool.com/misc/plugins/toonpoolcom15.src\',\'http://www.toonpool.com/misc/plugins/toonpoolcom15.png\',\'\',\'\');">Add a <strong>toonpool.com</strong> searchpanel to your browser.</a>');
  } else if (navigator.userAgent.toLowerCase().indexOf("opera") != -1) {
    document.write('<a href=\'opera:/edit/Search,"http://www.toonpool.com/gallery.php?search_qi=%s"\'>Add a <strong>toonpool.com</strong> searchpanel to your browser.</a><br />Just Drag & Drop the link above to your prefered position.');
  } else {
    document.write('Sorry, but your browser doesn\'t support this feature.');
  }
}


//E-Card Modul
function ecard(id,srcurl,srcurl2,ajaxurl,closehash,obj_name,bubbleid,shopPostcard) {
  this.id = id;
  this.bubbleid = bubbleid;
  this.srcurl = srcurl;
  this.srcurl2 = srcurl2;
  this.ajaxurl = ajaxurl;
  this.closehash = closehash;
  this.obj_name = obj_name;

  this.show = function() {
    layer.create('layer_0','',this.closehash);
    var d = '';
    //Layout:links
    d += "<div class='taf_left'><div id='thumbImg' class='taf_pict' style='display:table-cell; text-align:center; vertical-align:middle;'>";
    d += "<img src='"+srcurl+"' alt='ecard thumb' />";
    d += "</div>";
    if (shopPostcard) {
      d += "<br /><h3><a href='/postcardshop?imageid="+this.id+"' onclick='setDcookie();'>"+MO.ECARD_REAL_POSTCARD+"</a></h3>";
    }
    d += "</div>";
    //Layout:rechts
    d += "<div class='taf_text'>";
    d += "<h2>"+((this.bubbleid==0)?MO.ECARD_SEND:MO.ECARD_BUBBLE_SEND)+"</h2><br />"+MO.ECARD_HEAD+"<br /><br />";
    //Form
    d += "<form action='javascript:void(null);' id='ecardForm' onsubmit=\"if("+obj_name+".checkForm()){ajax.doRequest('"+ajaxurl+(ajaxurl.indexOf('?') == -1 ? '?' : '&')+"action=ecard'+ajax.getFormData('ecardForm'),true);}\"><div>";
    d += "<table style='border:none;'><tbody id='ecardTbody'>";
    d += "<tr><td>"+MO.ECARD_NAME+"</td><td colspan='2'><input type='text' name='sender_name' value='' /></td></tr>";
    d += "<tr><td>"+MO.ECARD_EMAIL+"</td><td colspan='2'><input type='text' name='sender_email' value='' /></td></tr>";
    d += "<tr><td>"+MO.ECARD_FRIENDS+"</td><td colspan='2'>&nbsp;</td></tr>";
    d += "<tr id='friend0'><td><a href='javascript:void("+obj_name+".addR());' title='"+MO.ECARD_ADD_ONE+"'>[+]</a> <a href='javascript:void("+obj_name+".removeR());' title='"+MO.ECARD_DEL_ONE+"'>[-]</td><td colspan='2'>"+MO.ECARD_RNAME+"&nbsp;<input type='text' name='reciever_name[]' id='reciever_name0' value=''>&nbsp;&nbsp;"+MO.ECARD_REMAIL+"&nbsp;<input type='text' name='reciever_email[]' value='' /></td></tr>"
    d += "<tr><td colspan='3'>&nbsp;</td></tr>";
    d += "<tr><td>"+MO.ECARD_TITLE+" <span class='small'>("+MO.ECARD_OPTIONAL+")</span></td><td colspan='2'><input type='text' name='title' value='' /></td></tr>";
    d += "<tr><td style='vertical-align:top;'>"+MO.ECARD_MSG+" <span class='small'>("+MO.ECARD_OPTIONAL+")</span></td><td colspan='2'><textarea name='message' rows='5' cols='40'></textarea></td></tr>";
    var now = new Date();
    var y = now.getFullYear();
    var m = now.getMonth() + 1;
    var day = now.getDate();
    d += "<tr><td>"+MO.ECARD_SENDON+"</td><td colspan='2'><select name='year' size='1'>";
    for (var end = y + 2, i = y; i < end; i++) {
      d += "<option value='"+i+"'>"+i+"&nbsp;&nbsp;</option>";
    }
    d += "</select>&nbsp;-&nbsp;<select name='month' size='1'>";
    for (var end = 13, i = 1; i < end; i++) {
      d += "<option value='"+i+"'"+((i != m)?'':" selected='selected'")+">"+((i<10)?'0':'')+i+"&nbsp;&nbsp;</option>";
    }
    d += "</select>&nbsp;-&nbsp;<select name='day' size='1'>";
    for (var end = 32, i = 1; i < end; i++) {
      d += "<option value='"+i+"'"+((i != day)?'':" selected='selected'")+">"+((i>=10)?'':'0')+i+"&nbsp;&nbsp;</option>";
    }
    d += "</select></td></tr>";
    d += "<tr><td style='text-align:right;'><input type='checkbox' name='send_n' id='send_n' checked='checked' /></td><td colspan='2'><label for='send_n'>"+MO.ECARD_NOTI_SENT+"</label></td></tr>";
    d += "<tr><td style='text-align:right;'><input type='checkbox' name='view_n' id='view_n' checked='checked' /></td><td colspan='2'><label for='view_n'>"+MO.ECARD_NOTI_SEEN+"</label></td></tr>";
    d += "<tr><td colspan='3' style='text-align:center;'><input type='submit' value='"+MO.ECARD_BUTTON_SEND+"' />&nbsp;<input type='button' value='"+MO.ECARD_BUTTON_PREVIEW+"' onclick='"+obj_name+".preview();' /><input type='hidden' name='id' value='"+this.id+"' /><input type='hidden' name='bubbleid' value='"+this.bubbleid+"' /></td></td></tr>";
    d += "</tbody></table>";
    d += "</div></form>";
    d += "</div><div class='cls'></div>";
    $('layer_0_content').innerHTML += d;
    layer.show('layer_0');
    if (crossBrowser.is_ie && (!crossBrowser.is_ie6)) { // Workaround für IE Bug (Bild vertikal mittig)
      var top = $('thumbImg').offsetParent.offsetWidth-$('thumbImg').childNodes[0].offsetWidth;
      top = (top - top % 2) / 2;
      $('thumbImg').childNodes[0].style.marginTop = top+'px';
    }
    ajaxnavi.setHash('#ecard');
  }
  this.preview = function() {
    var o,e,i,j,left;
    layer.create('layer_0_preview','z-index:9010;','');
    var d = '';
    //Layout
    d += "<div style='text-align:center;'>";//width:"+($('non_footer_general').offsetWidth - 60)+"px;
    d += MO.ECARD_PRE_HELLO+" "+$('reciever_name0').value+"<br />"+((this.bubbleid==0)?MO.ECARD_PRE_TITLE:MO.ECARD_PRE_BUBBLE_TITLE)+" "+$('ecardForm').sender_name.value+":<br /><br />";
		d += "<b>"+$('ecardForm').title.value+"</b><br /><br />";
		d += "<div id='ecardImg' style='position:relative; margin:0px; border:0px; padding:0px'><img src=\""+this.srcurl2+"\" alt=\"image\" /></div>";
		d += "<p style='text-align:left; margin:0 auto; width:500px; padding: 30px 0px 30px 0px;'>";
		d += $('ecardForm').message.value.replace(/\n/g,'<br />');//'
    d += "</p>";
		d += "<br />";
		d += "<input type='button' value='"+MO.ECARD_BUTTON_SEND+"' onclick=\"domHelpers.delElement('layer_0_preview');$('ecardForm').onsubmit();\" /> or <input type='button' value='"+MO.ECARD_BUTTON_CHANGE+"' onclick=\"domHelpers.delElement('layer_0_preview');\" />";
    d += "</div>";

    $('layer_0_preview_content').innerHTML += d;
    layer.show('layer_0_preview');
    if (this.bubbleid > 0) {
      i = 1;
      while (e = $('bubbleText_'+i)) {
        domHelpers.addElement($('ecardImg'),'div',{'id':'ecardText_'+i},{});
        o = $('ecardText_'+i);
        o.style.position = 'absolute';
        j = 0;
        while ($('ecardImg').childNodes[j].nodeName != 'IMG') { j++; } // Workaround Firefox Bug (#TEXT vor IMG)
        left = $('ecardImg').offsetParent.offsetWidth-$('ecardImg').childNodes[j].offsetWidth;
        left = (left - left % 2) / 2;
        if (crossBrowser.is_ie6) { // Workaround für IE6
          o.style.left = (parseInt(e.style.left)-$('bubbleDiv').offsetLeft)+'px';
        } else { // IE7, Firefox, Opera,...
          o.style.left = (parseInt(e.style.left)-$('bubbleDiv').offsetLeft+left-$('ecardImg').offsetLeft)+'px';
        }
        o.style.top = (parseInt(e.style.top)-$('bubbleDiv').offsetTop)+'px';
        o.style.width = parseInt(e.style.width)+'px';
        o.style.height = parseInt(e.style.height)+'px';
        o.style.fontSize = e.style.fontSize;
        o.style.fontFamily = e.style.fontFamily;
        o.style.color = e.style.color;
        o.style.backgroundColor = e.style.backgroundColor;
        o.style.textAlign = e.style.textAlign;
        o.innerHTML = e.innerHTML;
        i++;
      }
      if (crossBrowser.is_ie) { // Workaround für IE Bug (Bild ist ohne das hier nicht mittig)
        $('ecardImg').childNodes[0].style.marginLeft = (left-$('ecardImg').offsetLeft)+'px';
      }
    } else {
      if (crossBrowser.is_ie && (!crossBrowser.is_ie6)) { // Workaround für IE Bug (Bild ist ohne das hier nicht mittig)
        left = $('ecardImg').offsetParent.offsetWidth-$('ecardImg').childNodes[0].offsetWidth;
        left = (left - left % 2) / 2;
        $('ecardImg').childNodes[0].style.marginLeft = (left-$('ecardImg').offsetLeft)+'px';
      }
    }
  }

  this.checkForm = function() {
    var f = $('ecardForm');
    var anzE = f.elements.length;
    for (var i = 0; i < anzE; i++) {
      f.elements[i].className = '';
    }
    var noerror = true;
    if (f.sender_name.value == '') {
      noerror = false;
      f.sender_name.className = 'error';
    }
    if (f.sender_email.value == '' || !checkEmail(f.sender_email.value)) {
      noerror = false;
      f.sender_email.className = 'error';
    }
    anzE = f['reciever_name[]'].length;
    if (typeof anzE == 'undefined') {
      if (f['reciever_name[]'].value == '') {
        noerror = false;
        f['reciever_name[]'].className = 'error';
      }
      if (f['reciever_email[]'].value == '' || !checkEmail(f['reciever_email[]'].value)) {
        noerror = false;
        f['reciever_email[]'].className = 'error';
      }
    } else {
      for (var i = 0; i < anzE; i++) {
        if (f['reciever_name[]'][i].value == '') {
          noerror = false;
          f['reciever_name[]'][i].className = 'error';
        }
        if (f['reciever_email[]'][i].value == '' || !checkEmail(f['reciever_email[]'][i].value)) {
          noerror = false;
          f['reciever_email[]'][i].className = 'error';
        }
      }
    }

    if (!noerror) {
      alert(MO.ECARD_ERROR)
    }

    return noerror;
  }

  this.addR = function() {
    var max = 0;
    for (var i = 10; i > 0; i--) {
      if ($('friend'+i)) {
        max = i;
        break;
      }
    }
    if (max < 9) {
      var newTR = document.createElement('tr');
      newTR.setAttribute('id','friend'+(max+1));
      $('ecardTbody').insertBefore(newTR,$('friend'+max).nextSibling);
      var newTD = document.createElement('td');
      $('friend'+(max+1)).appendChild(newTD);
      newTD = document.createElement('td');
      newTD.setAttribute('colspan','2');
      $('friend'+(max+1)).appendChild(newTD);
      $('friend'+(max+1)).childNodes[0].innerHTML = '&nbsp;';
      $('friend'+(max+1)).childNodes[1].innerHTML = ""+MO.ECARD_RNAME+"&nbsp;<input type='text' name='reciever_name[]' value=''>&nbsp;&nbsp;"+MO.ECARD_REMAIL+"&nbsp;<input type='text' name='reciever_email[]' value='' />";
      //$('friend'+(max+1)).innerHTML = "<td>&nbsp;</td><td colspan='2'>"+MO.ECARD_RNAME+"&nbsp;<input type='text' name='reciever_name[]' value=''>&nbsp;&nbsp;"+MO.ECARD_REMAIL+"&nbsp;<input type='text' name='reciever_email[]' value='' /></td>";
    }
  }
  this.removeR = function(){
    for (var i = 10; i > 0; i--) {
      if ($('friend'+i)) {
        domHelpers.delElement('friend'+i);
        break;
      }
    }
  }
}

function img9(userid,name,imageuid,title,tags,obj_name,multi) {
  this.userid = userid;
  this.name = name;
  this.imageuid = imageuid;
  this.title = title;
  this.tags = tags;
  this.obj_name = obj_name;
  this.multi = multi;

  this.multi.link1 = 'javascript:void('+this.obj_name+'.navi(\'';
  this.multi.link2 = '\'));';

  this.show = function() {
    layer.create('layer_0','',"ajaxnavi.setHash('#');");
    var d = '';
    var imgsrc = "/user/"+this.userid+"/files/"+this.imageuid+"9.jpg";

    //Layout
    d += "<div style=\"text-align:center; width: 900px; height: 1050px;\">";
    d += "<h3>"+this.title+"</h3> "+MO.IMG9_BY+" <h3>"+this.name+"</h3>";
    if ($('strangerTeaser')) {
      d += $('strangerTeaser').innerHTML;
    }
    d += "<br />";

    if (this.multi !== false) {
      if (this.multi.actualPage > 1) {
        imgsrc = "/user/"+this.userid+"/pages/"+this.imageuid+"_page"+this.multi.actualPage+"_big.jpg";
      }
      d += '<div class="gal_navi" id="img9Navi1">'+tpgen.printNavi(this.multi.pages, 1, this.multi.actualPage, this.multi.link1, this.multi.link2)+'</div>';
    }

    d += "<br />";
    d += "<a class=\"a_img\" href=\"javascript:void(domHelpers.delElement('layer_0'));void(domHelpers.delElement('opacity'));ajaxnavi.setHash('#');\"><img id=\"img9img\" src=\""+imgsrc+"\" alt=\"Cartoon: "+this.title+" (large) by "+this.name+" tagged "+this.tags+"\" title=\""+this.title+" (large)\"/></a>";
    d += "</div>";

    if (this.multi !== false) {
      d += '<div class="gal_navi" id="img9Navi2">'+tpgen.printNavi(this.multi.pages, 1, this.multi.actualPage, this.multi.link1, this.multi.link2)+'</div>';
    }

    $('layer_0_content').innerHTML += d;
    layer.show('layer_0');
    ajaxnavi.setHash('#img9');
  };

  this.navi = function(data) {
    var search = /(\d+)/;
    search.exec(data);
    this.multi.actualPage = parseInt(RegExp.$1, 10);

    if (this.multi.actualPage != 1) {
      $('img9img').src = "/user/"+this.userid+"/pages/"+this.imageuid+"_page"+this.multi.actualPage+"_big.jpg";
    } else {
      $('img9img').src = "/user/"+this.userid+"/files/"+this.imageuid+"9.jpg";
    }

    $('img9Navi1').innerHTML = tpgen.printNavi(this.multi.pages, 1, this.multi.actualPage, this.multi.link1, this.multi.link2);
    $('img9Navi2').innerHTML = tpgen.printNavi(this.multi.pages, 1, this.multi.actualPage, this.multi.link1, this.multi.link2);
  };
}

function favorite(imageid,obj_name) {
  this.imageid = imageid;
  this.obj_name = obj_name;

  this.show = function() {
    layer.create('layer_0','',"ajaxnavi.setHash('#');");
    var d = '';
    //Layout
    d += "<form id=\"favoriteForm\" action=\"javascript:void(null);\" onsubmit=\"ajax.doRequest('/calls/showImageAjax.php?action=makeFavorite'+ajax.getFormData('favoriteForm'),true);\"><div style='width:450px;'>";
    d += "<strong>"+MO.FAV_TITLE+"</strong><br />";
    d += MO.FAV_WHY+"<br />";
    d += "<textarea cols=\"50\" rows=\"5\" name=\"favorite\" id=\"favoriteText\"></textarea><br />";
    d += "<input type=\"hidden\" name=\"imageid\" value=\""+this.imageid+"\" /><input style=\"display:block; margin: 5px auto;\" type=\"submit\" value=\""+MO.FAV_SUBMIT+"\" />";
    d += "</div></form>";

    $('layer_0_content').innerHTML += d;
    layer.show('layer_0');
    ajaxnavi.setHash('#addfavorite');
  }
}

function spam(imageid,obj_name) {
  this.imageid = imageid;
  this.obj_name = obj_name;

  this.show = function() {
    layer.create('layer_0','',"ajaxnavi.setHash('#');");
    var d = '';
    //Layout
    d += "<form id=\"reportForm\" action=\"javascript:void(null);\" onsubmit=\"ajax.doRequest('/calls/showImageAjax.php?action=spam'+ajax.getFormData('reportForm'),true);\"><div>";
    d += "<table style=\"border:none;\">";
    d += "<tr><td colspan=\"2\"><strong>"+MO.SPAM_TITLE+"</strong></td></tr>";
    d += "<tr><td><input type=\"radio\" name=\"spam_cat\" value=\"1\" id=\"radio_1\" /></td><td><label for=\"radio_1\">"+MO.SPAM_1+"</label></td></tr>";
    d += "<tr><td><input type=\"radio\" name=\"spam_cat\" value=\"2\" id=\"radio_2\" /></td><td><label for=\"radio_2\">"+MO.SPAM_2+"</label></td></tr>";
    d += "<tr><td><input type=\"radio\" name=\"spam_cat\" value=\"3\" id=\"radio_3\" /></td><td><label for=\"radio_3\">"+MO.SPAM_3+"</label></td></tr>";
    d += "<tr><td><input type=\"radio\" name=\"spam_cat\" value=\"4\" id=\"radio_4\" /></td><td><label for=\"radio_4\">"+MO.SPAM_4+"</label></td></tr>";
    d += "<tr><td><input type=\"radio\" name=\"spam_cat\" value=\"0\" id=\"radio_0\" /></td><td><label for=\"radio_0\">"+MO.SPAM_0+"</label></td></tr>";
    d += "<tr><td colspan=\"2\">"+MO.SPAM_REASON+"<br /><textarea cols=\"50\" rows=\"5\" name=\"reason\" id=\"reasonText\"></textarea></td></tr>";
    d += "<tr><td colspan=\"2\" style=\"text-align:center;\"><input type=\"submit\" value=\""+MO.SPAM_SUBMIT+"\" /><input type=\"hidden\" name=\"imageid\" value=\""+this.imageid+"\"></td></tr>";
    d += "</table>";
    d += "</div></form>";

    $('layer_0_content').innerHTML += d;
    layer.show('layer_0');
    ajaxnavi.setHash('#spam');
  }
}

function trans(imageid,imageuid,userid,userLoggedIn,languages,obj_name) {
  this.imageid = imageid;
  this.imageuid = imageuid;
  this.userid = userid;
  this.userLoggedIn = userLoggedIn;
  this.languages = languages;
  this.obj_name = obj_name;

  this.translations = new Array();

  this.show = function(edit,transId) {
    layer.create('layer_0','',"ajaxnavi.setHash('#');");
    var transChecked = false;
    var d = '';
    //Layout
    d += "<div style=\"width:360px; height:370px; float:left; overflow:auto;\">";
    d += "<h2>"+MO.TRANS_TITLE+"</h2><br />";
    d += "<strong>"+MO.TRANS_OTHER+"</strong><br />";
    var anzT = this.translations.length;
    if (anzT == 0) {
      d += MO.TRANS_FIRST;
    } else {
      var c = 0;
      for (var e in this.translations) {
        d += this.translations[e].long_desc+' '+MO.TRANS_BY+' '+this.translations[e].name+':<br />\'';
        d += this.translations[e].translation+'\'<br />';
        c++;
        if (c == 5) {
          break;
        }
      }
    }
    d += "</div>";
    d += "<div style=\"width:280px; height:250px; float:left;\">";
    d += "<img style=\"display:block; margin: 10px auto;\" src=\"/user/"+this.userid+"/thumbs/"+this.imageuid+".jpg\" alt=\""+this.imageuid+"\" />";
    d += "<form id=\"addTrans\" action=\"javascript:void(null);\" onsubmit=\"if("+obj_name+".checkForm()){ajax.doRequest('/calls/showImageAjax.php?action=addTrans'+ajax.getFormData('addTrans'),true);}\"><div>";
    d += "<table style=\"border:none;\">";
    d += this.printUserNotLoggedIn();
    d += "<tr><td style='vertical-align:top;'>"+MO.TRANS_NEW+"<br /><textarea cols=\"30\" rows=\"4\" name=\"translation\" id=\"translation\">";
    if (typeof edit == 'number' && edit == 1 && typeof transId == 'number' && typeof this.translations[transId] == 'object') {
      d += this.translations[transId].translation.replace(/<br \/>/g,'\n');
      transChecked = true;
    }
    d += "</textarea></td></tr>";
    d += "<tr><td><select name='language' size='1'>"+this.languages+"</select></td></tr>";
    d += "<tr><td style='text-align:right;'><input type='hidden' name='imageid' value='"+this.imageid+"' />";
    if (transChecked) {
      d += "<input type='hidden' name='translationid' value='"+transId+"' />";
    }
    d += "<input type='submit' value='"+MO.TRANS_SUBMIT+"' /></td></tr>";
    d += "</table>";
    d += "</div></form>";
    d += "</div>";
    d += "<div class=\"cls\"></div>";

    $('layer_0_content').innerHTML += d;
    if (transChecked) {
      changeSelect('addTrans','language',this.translations[transId].languageid);
    }
    layer.show('layer_0');
    ajaxnavi.setHash('#trans');
  }

  this.printUserNotLoggedIn = function() {
    if (this.userLoggedIn == 1) {
      return '';
    }
    var d = "<tr><td>"+MO.NOUSER_NAME+"</td></tr><tr><td><input type='text' name='user' id='userT' value='"+nouser_name+"' /></td></tr>";
    d += "<tr><td>"+MO.NOUSER_EMAIL+"</td></tr><tr><td><input type='text' id='emailT' name='email' value='"+nouser_email+"' /></td></tr>";
    return d;
  }

  this.toggle = function(index) {
    var s = '<p>'; 
    s += '<b>'+this.translations[index].long_desc+'</b> by ';
    s += (this.translations[index].userid > 0) ? '<a href="/artists/'+this.translations[index].name+'_'+this.translations[index].userid+'">'+this.translations[index].name+'</a>' : this.translations[index].name;
    s += ':<br />\''
    s += this.translations[index].translation+'\'<br />';
    if (this.translations[index].edit == 1) {
      s += "<a href=\"javascript:void(trans.show(1,"+index+"));\">["+MO.TRANS_EDIT+"]</a> <a href=\"javascript:void(null);\" onclick=\"if (confirm('"+MO.TRANS_DEL+"')) {ajax.doRequest('/calls/showImageAjax.php?action=delTrans&translationid="+index+"',true);}\">[X]</a><br />";
    }
    s += '</p>';
    $('translSPAN').innerHTML = s;
    return true;
  }

  this.checkForm = function() {
    var noerror = true;
    var info = '';
    if (this.userLoggedIn == 0) {
      if ($('userT').value == '') {
        info += MO.TRANS_CHECK1+'\n';
        noerror = false;
      }
      if ($('emailT').value == '' || !checkEmail($('emailT').value)) {
        info += MO.TRANS_CHECK2+'\n';
        noerror = false;
      }
    }
    if ($('translation').value == '') {
      info += MO.TRANS_CHECK3;
      noerror = false;
    }
    if (!noerror) {
      alert(info);
    }
    return noerror;
  }
}

var contact = {userid:0,username:'',action:''};
contact.init = function(userid,username,action) {
  contact.userid = userid;
  contact.username = username;
  contact.action = action;
};
contact.show = function() {
  layer.create('layer_0','','');
  switch (contact.action) {
  case 'save':
    var d = '';
    var jetzt = new Date();
    d += "<form id=\"contactForm\" action=\"javascript:void(null);\" onsubmit=\"ajax.doRequest('/calls/profileAjax.php?action=contact&contactaction="+contact.action+"&id="+contact.userid+"'+ajax.getFormData('contactForm'),true);\"><div class=\"img_comments\">";
    d += MO.CONTACT_ADD+" "+contact.username+" "+MO.CONTACT_TO+"<br />";
    d += "<input type=\"submit\" value=\""+MO.CONTACT_SUBMIT+"\" />";
    d += "</div></form>";
    break;

  case 'del':
    var d = '';
    d += php.sprintf(MO.CONTACT_DEL, contact.username)+"<br /><br /><input type='button' onclick=\"ajax.doRequest('/calls/profileAjax.php?action=contact&contactaction="+contact.action+"&id="+contact.userid+"');\" value='"+MO.CONTACT_DEL_SUBMIT+"' />";
    break;
  }

  $('layer_0_content').innerHTML = d;
  layer.show('layer_0');
};

var cotd = {imageid:0,userid:0,imageuid:'',title:'',original_x:0,original_y:0};
cotd.init = function(imageid,userid,imageuid,title,artist,tags,original_x,original_y) {
  cotd.imageid = imageid;
  cotd.userid = userid;
  cotd.imageuid = imageuid;
  cotd.title = title;
  cotd.artist = artist;
  cotd.tags = tags;
  cotd.original_x = original_x;
  cotd.original_y = original_y;
};
cotd.show = function() {
  if (cotd.imageid > 0) {
    layer.create('layer_0','text-align:center;','');
    var d = '';
    d += "<h3>"+MO.COTD_TITLE+"</h3><br />";
    d += "<a href=\""+printShowImageLink(cotd.imageid,cotd.title,'cartoons')+"\" onclick=\"setcookie('search=Newest')\">"+MO.COTD_DETAILS+"</a> | <a href=\"javascript:void(domHelpers.delElement('layer_0'));\" title=\""+MO.COTD_CLOSE_T+"\">"+MO.COTD_CLOSE+"</a><br />";
    d += "<a href=\"/toonservices.php\" title=\""+MO.COTD_SUB_T+"\">"+MO.COTD_SUB+"</a><br /><br />";
    var rF = 1;
    if (cotd.original_x > 500 || cotd.original_y > 500) {
      rF = Math.max(cotd.original_x/500,cotd.original_y/500);
    }
    var w = Math.floor(cotd.original_x/rF);
    var h = Math.floor(cotd.original_y/rF);
    d += "<a class='a_img' href=\""+printShowImageLink(cotd.imageid,cotd.title,'cartoons')+"\"><img style='width:"+w+"px; height:"+h+"px;' src=\"/user/"+cotd.userid+"/files/"+cotd.imageuid+"5.jpg\" title=\""+cotd.title+" (medium)\" alt=\"Cartoon: "+cotd.title+" (medium) by "+cotd.artist+" tagged "+cotd.tags+"\" /></a>";

    $('layer_0_content').innerHTML = d;
    layer.show('layer_0');
  }
};

var adminModule = {};
adminModule.select = {imageid:0,headline:'',review:''};
adminModule.select.init = function(imageid,headline,review) {
  adminModule.select.imageid = imageid;
  adminModule.select.headline = decodeURIComponent(headline);
  adminModule.select.review = decodeURIComponent(review);
};
adminModule.select.show = function() {
  layer.create('layer_0','','');

  var selectAction = (adminModule.select.headline == '' && adminModule.select.review == '') ? 'save' : 'editSave';

  var d = '';
  d += "<form id='selectForm' action='javascript:void(null);' onsubmit=\"ajax.doRequest('/admin/showImageAdmin.php?action=select&selectaction="+selectAction+"'+ajax.getFormData('selectForm'),true);\"><div class='img_comments'>";
  d += "<table cellpadding='0' cellspacing='0' style='border:none;'>";
  d += "<tr><td><strong>Write an artreview and make this cartoon SELECTED</strong></td></tr>";
  d += "<tr><td>headline:<input type='text' value='"+adminModule.select.headline+"' name='headline' size='40' /></td></tr>";
  d += "<tr><td>enter a review:<br /><textarea cols='50' rows='8' name='review'>"+adminModule.select.review+"</textarea></td></tr>";
  d += "<tr><td style='text-align:center;'><input type='submit' value='submit' /><input type='hidden' name='imageid' value='"+adminModule.select.imageid+"' /></td></tr>";
  d += "</table>";
  d += "</div></form>";

  $('layer_0_content').innerHTML = d;
  layer.show('layer_0');
};

var recomm = {};
recomm.show = function() {
  layer.create('layer_0','','');

  var d = '';
  d += '<form id="recomm_form" action="javascript:void(null);" onsubmit="ajax.doRequest(\'/calls/recommAjax.php?action=send\'+ajax.getFormData(\'recomm_form\'),true);"><div>';
  d += '<h2>'+MO.RECOMM_HEAD+'</h2><br />';
  d += '<table>';
  d += '<tr><td>'+MO.ECARD_NAME+'</td><td><input type="text" name="sname" value="" /></td></tr>';
  d += '<tr><td>'+MO.ECARD_FRIENDS+' '+MO.ECARD_REMAIL+'</td><td><input type="text" name="remail" value="" /></td></tr>';
  d += '<tr><td valign="top">'+MO.ECARD_MSG+'<br />(optional)</td><td><textarea name="msg" rows="5" cols="50"></textarea></td></tr>';
  d += '<tr><td colspan="2"><input type="submit" value="'+MO.ECARD_BUTTON_SEND+'" /><input type="hidden" name="link" value="'+window.location.href+'" /></td></tr>';
  d += '</table>';
  d += "</div></form>";

  $('layer_0_content').innerHTML = d;
  layer.show('layer_0');
};

var shop = {};
shop.previewData = [];
shop.showPreview = function(ind) {
  if (typeof ind == 'undefined') {
    var ind = 0;
  }

  if (typeof shop.previewData[ind] == 'undefined') {
    return;
  }
  var s = shop.previewData[ind];

  layer.create('layer_0','','');

  var d = '';
  d += '<div style="text-align:center; height: 600px;"><h2>'+MO.ECARD_BUTTON_PREVIEW+'</h2><br />';
  
  d += '<div style="height: 400px;"><img style="max-height: 400px; border: 1px solid #AFAFAF; padding: 1px; margin-top: 5px;" src="/user/'+s.userid+'/files/'+s.imageuid+'5.jpg" alt="" /></div><br />';

  d += shop.createNavi(ind);

  d += '</div>';

  $('layer_0_content').innerHTML = d;
  layer.show('layer_0');
};
shop.createNavi = function(ind) {
  var s = shop.previewData;

  var d = '';
  var mT = 0;
  for (var i = 0; i < s.length; i++) {
    mT = Math.floor((150 - s[i].thumb_y) / 2);
    d += '<div style="float:left; width: 130px; height: 150px; margin: 2px; text-align:center;"><a class="a_img" href="javascript:void(shop.showPreview('+i+'));"><img style="margin-top: '+mT+'px; border: 1px solid #AFAFAF; padding: 1px;" src="/user/'+s[i].userid+'/thumbs/'+s[i].imageuid+'.jpg" alt="" /></a></div>';
  }
  d += '<div class="cls"></div>';
  return d;
};

function newsletterModule(id) {
  this.id = id;

  this.init = function() {
    ajax.doRequest('/calls/newsletterAjax?action=init&newsletterid='+this.id+'&callback=newsletter.show', true);
  };

  this.show = function(d) {
    layer.create('layer_0','','');

    $('layer_0_content').innerHTML = d;
    layer.show('layer_0');
  };
}


var nouser = false;
var nouser_name = '';
var nouser_email = '';

var forum = {};
forum.bb = {};
forum.post = {};

/*
* forum.bb.ParseLogic
* -------------------
* Überprüft die übergebenen Tags auf Gültigkeit bzgl. der Schachtelung
*/
forum.bb.parseLogic = function (tags, b, e, isB, isI, isU, isImg, isUrl, isQuote) {
  var i, n, error;
  while (b < e) {
    while ((b < e) && (tags[b].type <= 0)) { b++; } // nächstes Tag
    if (b >= e) { break; } // Abbruch, wenn alle durch sind...
    // Anfangs-Tag (type 1 oder 2) gefunden, passendes Ende-Tag suchen...
    i = b+1;
    n = 1; // Verschachtelungstiefe
    while (i < e) {
      if (tags[b].tag == tags[i].tag) {
        if (tags[i].type >= 1) { n++; } // ein Level tiefer geschachtelt
        if (tags[i].type == 0) { --n; if (n == 0) { break; } }
      }
      i++;
    }
    if ((n == 0) && (i < e)) { // Tag-Paar (b,i) gefunden
      error = null;
      switch (tags[b].tag) {
        case 'b':
          if (isB > 0) { error = '[b] '+FO.PL_NOT_ALLOWED+' [b]'; }
          if (isImg > 0) { error = '[b] '+FO.PL_NOT_ALLOWED+' [img]'; }
          if (isUrl > 0) { error = '[b] '+FO.PL_NOT_ALLOWED+' [url]'; }
          isB++; break;
        case 'i':
          if (isI > 0) { error = '[i] '+FO.PL_NOT_ALLOWED+' [i]'; }
          if (isImg > 0) { error = '[i] '+FO.PL_NOT_ALLOWED+' [img]'; }
          if (isUrl > 0) { error = '[i] '+FO.PL_NOT_ALLOWED+' [url]'; }
          isI++; break;
        case 'u':
          if (isU > 0) { error = '[u] '+FO.PL_NOT_ALLOWED+' [u]'; }
          if (isImg > 0) { error = '[u] '+FO.PL_NOT_ALLOWED+' [img]'; }
          if (isUrl > 0) { error = '[u] '+FO.PL_NOT_ALLOWED+' [url]'; }
          isU++; break;
        case 'img':
          if (isImg > 0) { error = '[img] '+FO.PL_NOT_ALLOWED+' [img]'; }
          isImg++; break;
        case 'url':
          if (isImg > 0) { error = '[url] '+FO.PL_NOT_ALLOWED+' [img]'; }
          if (isUrl > 0) { error = '[url] '+FO.PL_NOT_ALLOWED+' [url]'; }
          isUrl++; break;
        case 'quote':
          if (isB > 0) { error = '[quote] '+FO.PL_NOT_ALLOWED+' [b]'; }
          if (isI > 0) { error = '[quote] '+FO.PL_NOT_ALLOWED+' [i]'; }
          if (isU > 0) { error = '[quote] '+FO.PL_NOT_ALLOWED+' [u]'; }
          if (isImg > 0) { error = '[quote] '+FO.PL_NOT_ALLOWED+' [img]'; }
          if (isUrl > 0) { error = '[quote] '+FO.PL_NOT_ALLOWED+' [url]'; }
          if (isQuote >= 3) { error = '[quote] '+FO.PL_TOO_DEEP; }
          isQuote++; break;
      }
      if (error !== null) {
        tags[b].type = -1; tags[b].error = error;
        tags[i].type = -1; tags[i].error = FO.PL_END_TAG;
        b++; // mit dem nächsten möglichen Tag weitermachen
        break;
      }
      forum.bb.parseLogic(tags,b+1,i,isB,isI,isU,isImg,isUrl,isQuote); // innere Logik-Struktur prüfen
      switch (tags[b].tag) {
        case 'b': --isB; break;
        case 'i': --isI; break;
        case 'u': --isU; break;
        case 'img': --isImg; break;
        case 'url': --isUrl; break;
        case 'quote': --isQuote; break;
      }
      b = i+1; // weiter nach dem Ende-Tag
    } else {
      b++; // ??? fehlendes Ende-Tag für Anfangs-Tag mit type>0 ???
    }
  }
};

/*
* forum.bb.ParseNesting
* ---------------------
* Überprüft die Schachtelung von übergebenen Tags und markiert
* fehlende Anfangs- und Ende-Tags
*/
forum.bb.parseNesting = function (tags, b, e) {
  var i, n;
  while (b < e) {
    while ((b < e) && (tags[b].type <= 0)) {
      if (tags[b].type == 0) {
        tags[b].type = -1; // ggf. Ende-Tags ignorieren, weil wir keine fehlenden Anfangs-Tags einfügen!
        tags[b].error = FO.PN_END_BEGIN;
      }
      b++; // nächstes Tag
    }
    if (b >= e) { break; } // Abbruch, wenn alle durch sind...
    // Anfangs-Tag (type 1 oder 2) gefunden, passendes Ende-Tag suchen...
    i = b+1;
    n = 1; // Verschachtelungstiefe
    while (i < e) {
      if (tags[b].tag == tags[i].tag) {
        if (tags[i].type >= 1) { n++; } // ein Level tiefer geschachtelt
        else if (tags[i].type == 0) { --n; if (n == 0) { break; } }
      }
      i++;
    }
    if ((n == 0) && (i < e)) { // Tag-Paar (b,i) gefunden
      forum.bb.parseNesting(tags,b+1,i); // innere Tag-Struktur prüfen
      b = i+1;
    } else {
      // fehlendes Ende-Tag, also Tag ignorieren!!!
      tags[b].type = -1;
      tags[b].error = FO.PN_BEGIN_END;
      b++; // mit dem Rest weiterversuchen...
    }
  }
};

/*
* forum.bb.ParseTags
* ------------------
* Findet Tags und überprüft ggf. mit Negativ-Liste
*/
forum.bb.parseTags = function (text, tags, negativTags) {
  var type, tag, pos, next, attr, error;
  var len, hasAttr, t;
  len = text.length;
  pos = 0;
  while (pos < len) {
    next = text.indexOf('[',pos); // absoluter Offset
    if (next == -1) { break; } // keine weiteren Tags mehr
    end = text.indexOf(']',next); // erstes "]" nach "[" suchen..., absoluter Offset
    if (end == -1) { break; } // Rest ignorieren, kein "]" gefunden...
    tag = text.substring(next+1,end);
    if (tag.substring(0,1) == '/') { // Ende-Tag
      type = 0;
      tag = tag.substring(1,tag.length);
      attr = null;
      error = null;
    } else { // Anfangs-Tag
      hasAttr = tag.indexOf('=');
      if (hasAttr == -1) { // ohne Attribut
        type = 1;
        attr = null;
        error = null;
      } else { // mit Attribut
        type = 2;
        attr = tag.substring(hasAttr+1,tag.length);
        tag = tag.substring(0,hasAttr);
        error = null;
      }
    }
    tag = tag.toLowerCase();
    if ((tag != 'b') && (tag != 'i') && (tag != 'u') && (tag != 'img') && (tag != 'url') && (tag != 'quote')) {
      type = -1;
      error = FO.PT_UNKNOWN+' ['+tag+']'; // es werden nur die o.g. Tags unterstützt
    } else {
      for (t = 0; ((t < negativTags.length) && (negativTags[t] != tag)); t++) {};
      if (t < negativTags.length) { // verbotenes Tag gefunden
        type = -1;
        error = FO.PT_FORBIDDEN+' ['+tag+']';
      }
    }
    t = tags.length;
    tags[t] = new Object;
    tags[t].type = type;
    tags[t].tag = tag;
    tags[t].pos = next;
    tags[t].next = end+1;
    tags[t].attr = attr;
    tags[t].error = error;
    pos = end+1;
  }
};

/*
* forum.bb.replaceText
* --------------------
* ersetzt BBCode-Tags durch entsprechende HTML-Tags
*/
forum.bb.replaceText = function (replace, text, beg, end, tags, b, e) {
  var s, next;
  s = '';
  while (beg < end) {
    while ((b < e) && ((tags[b].type < 0) || (tags[b].pos < beg))) {
      b++; // nächstes gültiges Begin- oder Ende-Tag suchen
    }
    if (b >= e) {
      next = end; // keine weiteren Tags
    } else {
      next = tags[b].pos; // Position des nächsten Tags
    }
    if (beg < next) { // es gibt Text vor dem nächsten Tag
      s += text.substring(beg,next);
      beg = next;
    }
    if ((b < e) && (beg == next)) { // nun folgt ein Tag, also ersetzen
      if (tags[b].type == 0) { // Ende-Tag
        s += replace[tags[b].tag][2];
      } else if (tags[b].type == 1) { // Anfangs-Tag ohne Attribut
        s += replace[tags[b].tag][0];
        if (tags[b].tag == 'quote') {
          s += 'Quote:';
        } else {
          // nothing to do...
        }
        s += replace[tags[b].tag][1];
      } else if (tags[b].type == 2) { // Anfangs-Tag mit Attribut
        s += replace[tags[b].tag][0];
        if (tags[b].tag == 'quote') {
          s += tags[b].attr.replace(/\"/g,'&quot;').replace(/\'/g,'&#039;')+' wrote:';
        } else if ((tags[b].tag == 'img') || (tags[b].tag == 'url')) {
          s += tags[b].attr.replace(/\"/g,'&quot;').replace(/\'/g,'&#039;').replace(/\ /g,'%20');
        } else {
          // Attribut ignorieren bei b,i und u
        }
        s += replace[tags[b].tag][1];
      }
      beg = tags[b].next; // hinter dem Tag weitermachen
    }
  }
  return s;
};

/*
* forum.bb.validateTags
* ---------------------
* suchen und ersetzen von BB-Code Tags
*/
forum.bb.validateTags = function (text) {
  var tags,bbNegativTags,replace,bbReply,t;
  // ggf. HTML-Codierungen saubermachen
  text = text.replace(/</g,'&lt;').replace(/>/g,'&gt;'); /*** Spitze Klammern ersetzen!!! ***/
  // Negativ-Tags
  bbNegativTags = new Array(); // bbNegativTags = new Array('img','url');
  // Feststellen, welche Tags überhaupt vorhanden sind...
  tags = new Array();
  forum.bb.parseTags(text,tags,bbNegativTags);
  // Feststellen der fehlenden Begin- und Ende-Tags
  forum.bb.parseNesting(tags,0,tags.length);
  // Überprüfen der Logik, ggf. Tags ignorieren, wenn unzulässig
  forum.bb.parseLogic(tags,0,tags.length,0,0,0,0,0,0);
  // Ersetzung des BBCode durch HTML-Code
  replace = new Object();
  replace['b'] = new Array('<b>', '', '</b>');
  replace['i'] = new Array('<i>', '', '</i>');
  replace['u'] = new Array('<u>', '', '</u>');
  replace['quote'] = new Array('<div class="quote"><b>', '</b><br />', '</div>');
  replace['img'] = new Array('<img src="','" alt="','" />');
  replace['url'] = new Array('<a href="', '" onclick="window.open(this.href); return false;" rel="nofollow">', '</a>');
  bbReply = forum.bb.replaceText(replace,text,0,text.length,tags,0,tags.length);
  bbReply = bbReply.replace(/\r?\n/g,'<br />');
  // Fehlerbehandlung
  forum.bb.bbErrors = '';
  for (t=0; t<tags.length; t++) {
    if (tags[t]['type'] == -1) {
      forum.bb.bbErrors += ((forum.bb.bbErrors == '')?'':',  ')+'Position '+tags[t]['pos']+':'+tags[t]['error'];
    }
  }
  // Ergebnis zurückliefern...
  return bbReply;
};

forum.bb.insertSimple = function(code) {
  var bbcode = '['+code+'][/'+code+']';
  forum.bb.insertAtCursor(bbcode);
};

forum.bb.insertPrompt = function(code) {
  var txt = {'img':['Please enter the url for the image:','Please enter a title for the image:','title'],'url':['Please enter the url:','Please enter a text, where everybody can click on:','click']};
  var t1 = window.prompt(txt[code][0],'http://');
  if (t1) {
    var t2 = window.prompt(txt[code][1],txt[code][2]);
    if (t2) {
      var bbcode = '['+code+'='+t1.replace(/\ /g,'%20')+']'+t2+'[/'+code+']';
      forum.bb.insertAtCursor(bbcode);
    }
  }
};

forum.bb.insertAtCursor = function(data) {
  var p = $('newPostForm').post_text;
  if (document.selection) {
    p.focus();
    var sel = document.selection.createRange();
    sel.text = data;
  } else if (p.selectionStart || p.selectionStart == 0) {
    p.value = p.value.substring(0, p.selectionStart) + data + p.value.substring(p.selectionEnd, p.value.length);
  } else {
    p.value += data;
  }
  p.focus();
};
forum.bb.unparse = function(data) {
  data = data.replace(/\n/gi,"");
  data = data.replace(/\r/gi,"");

  data = data.replace(/<a\s+.*?href="(.*?)".*?>(.*?)<\/a>/gi,'[url=$1]$2[/url]');
  data = data.replace(/<img\s*src="(.*?)"\s*alt="(.*?)"\s*\/?>/gi,'[img=$1]$2[/img]');
  data = data.replace(/<img\s*alt="(.*?)"\s*src="(.*?)"\s*\/?>/gi,'[img=$2]$1[/img]');
  data = data.replace(/<img\s*src="(.*?)"\s*alt=(.*?)\s*\/?>/gi,'[img=$1]$2[/img]'); // IE-Bug workaround
  data = data.replace(/<img\s*alt=(.*?)\s*src="(.*?)"\s*\/?>/gi,'[img=$2]$1[/img]'); // IE-Bug workaround
  data = data.replace(/<img\s*src="(.*?)"\s*\/?>/gi,'[img=$1]$1[/img]');

  data = data.replace(/<div class="quote"><b>(.*?)\s+wrote:<\/b><br\s*\/?>/gi,'[quote=$1]');
  data = data.replace(/<div class="quote"><b>Quote:<\/b><br\s*\/?>/gi,'[quote]');
  data = data.replace(/<div class=quote><b>(.*?)\s+wrote:<\/b><br\s*\/?>/gi,'[quote=$1]'); // IE-Bug workaround
  data = data.replace(/<div class=quote><b>Quote:<\/b><br\s*\/?>/gi,'[quote]'); // IE-Bug workaround
  data = data.replace(/<\/div>/gi,'[/quote]');

  data = data.replace(/<br\s*\/?>/gi,"\r\n");
  data = data.replace(/<(b|u|i|\/b|\/u|\/i)>/gi,'[$1]');

  data = data.replace(/^\s+/, '').replace (/\s+$/, '');

  // für Quotings werden die Sonderzeichen & < > von html-Codierung in einfache Zeichen umgewandelt,
  // weil sie nicht mit innerHTML, sondern als value-Zuweisung verwendet werden.
  data = data.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
  data = data.replace(/&quot;/g, '"').replace(/&#039;/g, "'");

  return data;
};
forum.bb.createButtons = function() {
  var html = '';
  html += "<a class='a_img' href=\"javascript:void(forum.bb.insertSimple('b'));\"><img src='/forum/pics/style/bold.gif' alt='bold' title='bold' /></a>&nbsp;";
  html += "<a class='a_img' href=\"javascript:void(forum.bb.insertSimple('i'));\"><img src='/forum/pics/style/italic.gif' alt='italic' title='italic' /></a>&nbsp;";
  html += "<a class='a_img' href=\"javascript:void(forum.bb.insertSimple('u'));\"><img src='/forum/pics/style/underline.gif' alt='undeline' title='underline' /></a>&nbsp;";
  html += "<a class='a_img' href=\"javascript:void(forum.bb.insertSimple('quote'));\"><img src='/forum/pics/style/quote.gif' alt='quote' title='quote' /></a>&nbsp;";
  html += "<a class='a_img' href=\"javascript:void(forum.bb.insertPrompt('img'));\"><img src='/forum/pics/style/image.gif' alt='image' title='image' /></a>&nbsp;";
  html += "<a class='a_img' href=\"javascript:void(forum.bb.insertPrompt('url'));\"><img src='/forum/pics/style/link.gif' alt='hyperlink' title='hyperlink' /></a>&nbsp;";
  return html;
};

forum.post.reply = function(destId,onsubmit,isTopic,isPost,isEdit,isQuote,editId,quoteSource,quoteName) {
  if ($('newPostForm')) {
    $('newPostForm').parentNode.innerHTML = '&nbsp;';
  }
  var p = $(destId);
  p.innerHTML = forum.post.createForm(destId,onsubmit,isTopic,isPost,isEdit,editId);
  if (isQuote) {
    var qs = isEdit ? '' : '[quote='+quoteName+']';
    var qe = isEdit ? '' : '[/quote]';
    $('newPostForm').post_text.value = qs+forum.bb.unparse($(quoteSource).innerHTML)+qe;
  }
  $('newPostForm').post_text.focus();
};

forum.post.createForm = function(destId,onsubmit,isTopic,isPost,isEdit,editId) {
  //destId: Wo schreiben wir die Form rein
  //onsubmit: submitHandler
  //isTopic: true wenns ein neues Topic ist
  //isPost: true wenns ein neuer Beitrag ist
  //isEdit: true wenn man editiert
  //editId: bei isEdit: die id des Beitrages, bei isTopic: boardid des boards wo der topic erstellt wird sonst die id des Topics/image/profile
  var html = '';
  html = "<form id='newPostForm' action=\"javascript:void(null);\" onsubmit=\"$('newPostForm').newPostSubmit.disabled = true;"+onsubmit+"\"><div>\n";
  html += "<table style='background-color: #F0F1FA; width: 99%;' cellpadding='0' cellspacing='0'>\n<tr><td class='light'>";
  if (isTopic) {
    html += "<input type='hidden' name='boardid' value='"+editId+"' />"+FO.CF_SUBJECT+"</td><td class='light'><input type='text' name='topic_title' value='' size='60' /></td></tr>\n<tr><td class='light'>";
  } else if (isEdit) {
    html += "<input type='hidden' name='postid' value='"+editId+"' />";
  } else {
    html += "<input type='hidden' name='topicid' value='"+editId+"' />";
  }
  html += FO.CF_STYLE+"</td><td class='light'>"+forum.bb.createButtons()+"</td></tr>\n";
  if (nouser) {
    html += "<tr><td class='light'>&nbsp;</td><td class='light'>"+FO.NOUSER_NAME+"<br /><input type='text' name='guest_name' value='"+nouser_name+"' /></td></tr>\n";
    html += "<tr><td class='light'>&nbsp;</td><td class='light'>"+FO.NOUSER_EMAIL+"<br /><input type='text' name='guest_email' value='"+nouser_email+"' /></td></tr>\n";
  }
  html += "<tr><td class='light' valign='top'>"+FO.CF_MSG+"</td><td class='light' style='width:100%;'><textarea name='post_text' style='width:97%;' rows='5'></textarea></td></tr>\n";
  html += "<tr><td class='light' colspan='2' style='padding-left:20px;'>&nbsp;&nbsp;&nbsp;&nbsp;<input type='button' value='"+FO.CF_PREVIEW+"' onclick='forum.post.preview();' /></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type='submit' value='"+FO.CF_SUBMIT+"' name='newPostSubmit' />&nbsp;&nbsp;<input type='button' value='"+FO.CF_CANCEL+"' onclick=\"forum.post.cancel('"+destId+"');\" /></td></tr>\n";
  html += "</table></div></form>\n";

  html += "<table style='width: 87%; margin-left:40px; background-color: #F0F1FA; border:1px dashed #777777; display:none;' cellpadding='0' cellspacing='0' id='previewPostTable'>\n";
  html += "<tr><td class='light'><b>"+FO.CF_POST_PREVIEW+":</b></td></tr>\n";
  html += "<tr><td class='light fored' id='previewPostErrors'></td></tr>\n";
  html += "<tr><td class='light' style='padding-left:40px;' id='previewPostTd'></td></tr>\n";
  html += "</table>\n";
  return html;
};
forum.post.preview = function() {
  var source = $('newPostForm').post_text.value;
  $('previewPostTd').innerHTML = forum.bb.validateTags(source); // BBCode in HTML-Code übersetzen
  $('previewPostErrors').innerHTML = forum.bb.bbErrors; // ggf. Fehlermeldung(en) anzeigen
  $('previewPostTable').style.display = '';
};
forum.post.cancel = function(id) {
  $(id).innerHTML = '&nbsp;';
};


var toonpool = {};
//user-config
toonpool.c = {};
//iframe
toonpool.i = {};
toonpool.i.src = 'http://www.toonpool.com/misc/plugins/toonpool_gadget.php';
toonpool.i.id = 'toonpoolIframe';
toonpool.i.height = 190;
toonpool.i.width = 120;
toonpool.i['border-width'] = '0';
toonpool.i['border-color'] = '#46415c';
toonpool.i['border-style'] = 'none';

toonpool.i.write = function() {
  var d = "";
  d += "<iframe ";
  d += "frameborder='0' ";//IE sucks
  d += "allowtransparency='true' ";//IE sucks
  d += "framespacing='0'";//IE6 sucks
  d += "id="+toonpool.i.id+" ";
  d += "style='height:"+toonpool.i.height+"px; width:"+toonpool.i.width+"px;border-width:"+toonpool.i['border-width']+"px;border-color:"+toonpool.i['border-color']+";border-style:"+toonpool.i['border-style']+";' ";
  d += "src='"+toonpool.i.src+toonpool.i.createQuery()+"'";
  d += "</iframe>";
  return d;
};

toonpool.i.createQuery = function() {
  var q = [];
  for (var v in toonpool.c) {
    q.push(v+'='+encodeURIComponent(toonpool.c[v]));
  }
  return q.length == 0 ? '' : '?'+q.join('&');
};

//Slideshow
toonpool.s = {};
toonpool.s.timer = null;
toonpool.s.speed = 8000;
toonpool.s.slide = true;
toonpool.s.preloaded = null;
toonpool.s.pics = [];
toonpool.s.h = 130;
toonpool.s.w = 100;
toonpool.s.fullsize = false;

toonpool.s.printLogo = function() {
  var t = Math.floor((toonpool.s.h - 90) / 2 + 10)+'px';
  var l = Math.floor((toonpool.s.w - 74) / 2 + 10)+'px';
  document.getElementById('imageHolder').innerHTML = "<a class='a_img' href='http://www.toonpool.com/' onclick='window.open(this.href); return false;'><img style='position:relative; border:none; top:"+t+"; left:"+l+";' src='http://www.toonpool.com/misc/pics/general/gadgetloader.gif' alt='toonpool.com' /></a>";
};

toonpool.s.preload = function() {
  var tp = toonpool;
  if (tp.s.pics.length == 0) {
    tp.s.preloaded = null;
    return;
  }
  var p = tp.s.pics.shift();
  var nA = document.createElement('a');
  nA.setAttribute('href',p.href);
  nA.setAttribute('class','a_img');
  nA.setAttribute('onclick','window.open(this.href); return false;');
  var nIMG = document.createElement('img');
  var r = 1;
  if (toonpool.s.fullsize) {
    r = Math.max(Math.max(p.height/500,p.width/500),1);
  }
  var t = Math.floor((toonpool.s.h - p.height/r) / 2 + 10)+'px';
  var l = Math.floor((toonpool.s.w - p.width/r) / 2 + 10)+'px';
  nIMG.setAttribute('style','position:relative; border:none; top:'+t+'; left:'+l);
  if (navigator.userAgent.toLowerCase().indexOf('msie') != -1) {//IE sucks
    nA.setAttribute('className','a_img');
    nA.onclick = function() {window.open(this.href); return false;};
    nIMG.style.setAttribute('cssText', 'position:relative; border:none; top:'+t+'; left:'+l);
  }
  nIMG.setAttribute('src',p.src);
  nIMG.setAttribute('title',p.title);
  nIMG.setAttribute('alt',p.title);
  nA.appendChild(nIMG);
  tp.s.preloaded = nA;
};

toonpool.s.init = function() {
  toonpool.s.printLogo();
  toonpool.s.preload();
  if (!toonpool.s.slide) {
    toonpool.s.timer = window.setTimeout(function(){document.getElementById('imageHolder').innerHTML = '';document.getElementById('imageHolder').appendChild(toonpool.s.preloaded);},(toonpool.s.speed / 2 ));
    return;
  }
  toonpool.s.timer = window.setTimeout(toonpool.s.showThumb,(toonpool.s.speed / 2 ));
};

toonpool.s.showThumb = function() {
  if (toonpool.s.preloaded == null) {
    return;
  }
  document.getElementById('imageHolder').innerHTML = '';
  document.getElementById('imageHolder').appendChild(toonpool.s.preloaded);
  toonpool.s.preload();
  if (toonpool.s.preloaded != null) {
    toonpool.s.timer = window.setTimeout(toonpool.s.showThumb,toonpool.s.speed);
  } else {
    toonpool.s.timer = window.setTimeout(function(){window.location.reload();},toonpool.s.speed);
  }
};


colorWindow = new Object();

colorWindow.toHex = function (n,l) {
  var s,i;
  s = '';
  while (l>0) {
    i = n % 16;
    s = colorWindow.toHex.digit[i]+s;
    n = (n-i)/16;
    l--;
  }
  return s;
};
colorWindow.toHex.digit = new Array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');

colorWindow.toInt = function (s) {
  var n,i;
  if (s.substr(0,1) == '#') {
    s = s.substr(1);
  }
  n = 0;
  while (s != '') {
    i = colorWindow.toInt.digits.indexOf(s.substr(0,1).toUpperCase());
    if (i == -1) {
      s = '';
      n = 0;
    } else {
      s = s.substr(1);
      n = n * 16 + i;
    }
  }
  return n;
};
colorWindow.toInt.digits = '0123456789ABCDEF';

colorWindow.hide = function () {
  $('colorWindow').style.visibility = 'hidden';
  w = $('colorWindow');
  crossBrowser.removeEvent(w,'mousedown',colorWindow.mousedown);
  crossBrowser.removeEvent(w,'mousemove',colorWindow.mousemove);
  crossBrowser.removeEvent(document,'mouseup',colorWindow.mouseup);
};

colorWindow.mousemove = function (e) {
  var r,g,b,c;
  if (colorWindow.rgb_mouse) {
    var pos = crossBrowser.getMousePos(e);
    pos.x -= colorWindow.rgb_clipX;;
    pos.y -= colorWindow.rgb_clipY;
    r = $('rgb_r').value;
    g = $('rgb_g').value;
    b = $('rgb_b').value;
    if ((pos.x >= 4) && (pos.x <= 67) && (pos.y >= 4) && (pos.y <= 259)) {
      r = 259-pos.y;
    } else if ((pos.x >= 72) && (pos.x <= 135) && (pos.y >= 4) && (pos.y <= 259)) {
      g = 259-pos.y;
    } else if ((pos.x >= 140) && (pos.x <= 203) && (pos.y >= 4) && (pos.y <= 259)) {
      b = 259-pos.y;
    } else if ((pos.x >= 4) && (pos.x <= 101) && (pos.y >= 296) && (pos.y <= 323)) {
      r = 0; g = 0; b = 0;
    } else if ((pos.x >= 106) && (pos.x <= 203) && (pos.y >= 296) && (pos.y <= 323)) {
      r = 255; g = 255; b = 255;
    }
    $('rgb_r').value = r;
    $('rgb_g').value = g;
    $('rgb_b').value = b;
    $('rgb_r_marker').style.top = (258-r)+'px';
    $('rgb_g_marker').style.top = (258-g)+'px';
    $('rgb_b_marker').style.top = (258-b)+'px';
    $('rgb_disp').style.backgroundColor = '#'+colorWindow.toHex(r,2)+colorWindow.toHex(g,2)+colorWindow.toHex(b,2);
  }
};

colorWindow.mousedown = function (e) {
  colorWindow.rgb_mouse = true;
  colorWindow.mousemove(e);
};

colorWindow.mouseup = function (e) {
  colorWindow.mousemove(e);
  colorWindow.rgb_mouse = false;
};

colorWindow.applyColor = function () {
  var c = parseInt($('rgb_r').value)*65536+parseInt($('rgb_g').value)*256+parseInt($('rgb_b').value);
  colorWindow.hide();
  eval(colorWindow.callback+'('+c+');');
};

colorWindow.show = function (c,callback,bgcolor,txtApply,txtCancel) {
  var s,i,x,y,w,r,g,b;
  b = c % 256;
  g = ((c - b) / 256) % 256;
  r = (((c - b) / 256) - g) / 256;
  x = (mouse.x < 208) ? 0 : mouse.x-208;
  y = (mouse.y < 356) ? 0 : mouse.y-356;
  if (!$('colorWindow')) {
    domHelpers.addElement(document.body,'div',{'id':'colorWindow'},{});
    w = $('colorWindow');
    w.style.zIndex = 9000;
    w.style.position = 'absolute';
    w.style.cursor = 'pointer';
    w.style.padding = '0px';
    w.style.margin = '0px';
    w.style.border = '0px';
    w.style.backgroundColor = bgcolor;
    w.style.color = '#000000';
    w.style.left = x+'px';
    w.style.top = y+'px';
    w.style.width = '208px';
    w.style.height = '356px';
    s = '<div id="rgb_disp_r" style="position:absolute; top:4px; left:4px; width:64px; height:256px;">';
    for (i=255; i>=0; i--) {
      s += '<div class="one_px" style="width:64px; background-color:#'+colorWindow.toHex(i,2)+'0000">&nbsp;</div>';
    }
    s += '</div>';
    s += '<div id="rgb_r_marker" name="rgb_r_marker" style="position:absolute; top:'+(258-r)+'px; left:4px; width:64px; height:3px; font-size:3px; line-height:3px; background-color:#FFFFFF; cursor:pointer;" >&nbsp;</div>';
    s += '<div id="rgb_disp_g" style="position:absolute; top:4px; left:72px; width:64px; height:256px;">';
    for (i=255; i>=0; i--) {
      s += '<div class="one_px" style="width:64px; background-color:#00'+colorWindow.toHex(i,2)+'00">&nbsp;</div>';
    }
    s += '</div>';
    s += '<div id="rgb_g_marker" name="rgb_g_marker" style="position:absolute; top:'+(258-g)+'px; left:72px; width:64px; height:3px; font-size:3px; line-height:3px; background-color:#FFFFFF; cursor:pointer;" >&nbsp;</div>';
    s += '<div id="rgb_disp_b" style="position:absolute; top:4px; left:140px; width:64px; height:256px;">';
    for (i=255; i>=0; i--) {
      s += '<div class="one_px" style="width:64px; background-color:#0000'+colorWindow.toHex(i,2)+'">&nbsp;</div>';
    }
    s += '</div>';
    s += '<div id="rgb_b_marker" name="rgb_b_marker" style="position:absolute; top:'+(258-b)+'px; left:140px; width:64px; height:3px; font-size:3px; line-height:3px; background-color:#FFFFFF; cursor:pointer;" >&nbsp;</div>';
    s += '<div id="rgb_disp" style="position:absolute; top:264px; left:4px; width:200px; height:28px; color:#000000; background-color:#FFFFFF"></div>';
    s += '<div style="position:absolute; top:296px; left:4px; width:98px; height:28px; color:#000000; background-color:#000000;"></div>';
    s += '<div style="position:absolute; top:296px; left:106px; width:98px; height:28px; color:#000000; background-color:#FFFFFF;"></div>';
    s += '<div style="position:absolute; top:328px; left:4px; width:200px; height:28px; color:#000000;">';
    s += '<form id="rgb_form" name="rgb_form" action="javascript:return false;" method="POST">';
    s += '  <input id="rgb_r" name="rgb_r" type="hidden" value="'+r+'" />';
    s += '  <input id="rgb_g" name="rgb_g" type="hidden" value="'+g+'" />';
    s += '  <input id="rgb_b" name="rgb_b" type="hidden" value="'+b+'" />';
    s += '  <div style="float:left;"><input type="button" value="'+txtCancel+'" onclick="javascript:colorWindow.hide();" /></div>';
    s += '  <div style="float:right;"><input type="button" value="'+txtApply+'" onclick="javascript:colorWindow.applyColor();" /></div>';
    s += '</form>';
    s += '</div>';
    w.innerHTML = s;
    colorWindow.rgb_mouse = false;
  } else {
    w = $('colorWindow');
    w.style.left = x+'px';
    w.style.top = y+'px';
    $('rgb_r').value = r;
    $('rgb_g').value = g;
    $('rgb_b').value = b;
  }
  colorWindow.callback = callback;
  colorWindow.rgb_clipX = w.offsetLeft;
  colorWindow.rgb_clipY = w.offsetTop;
  $('rgb_r_marker').style.top = (258-r)+'px';
  $('rgb_g_marker').style.top = (258-g)+'px';
  $('rgb_b_marker').style.top = (258-b)+'px';
  $('rgb_disp').style.backgroundColor = '#'+colorWindow.toHex(r,2)+colorWindow.toHex(g,2)+colorWindow.toHex(b,2);
  w.style.visibility = 'visible';
  crossBrowser.addEvent(w,'mousedown',colorWindow.mousedown);
  crossBrowser.addEvent(w,'mousemove',colorWindow.mousemove);
  crossBrowser.addEvent(document,'mouseup',colorWindow.mouseup);
};




var bubble = {};

//crossBrowser.addEvent(document,'mouseup',function(){dragobject = null; changesizeobject = null; bubble.rgb_mouse = false; });

bubble.index = 0;
bubble.selected = -1;
bubble.selectedColor = '#EEEE55';
bubble.normalColor = '#888888';
bubble.font = new Array();
bubble.rgb_mouse = false;

bubble.init = function (imageid,bubbleid) {
  bubble.imageid = imageid;
  bubble.bubbleid = bubbleid;
  bubble.state = true;
};

bubble.initClipping = function() {
  var e;
  bubble.clip = {};
  e = $('bubbleImage');
  bubble.clip.lx = e.offsetWidth;
  bubble.clip.ly = e.offsetHeight;
  bubble.clip.x1 = e.offsetLeft;
  bubble.clip.y1 = e.offsetTop-20;
  bubble.clip.x2 = bubble.clip.x1+bubble.clip.lx+4;
  bubble.clip.y2 = bubble.clip.y1+bubble.clip.ly+22;
};

bubble.downDrag = function(index) {
  drag.start($('bubbleText_'+index),
             [{'element':document,'type':'mousemove','func':bubble.moveDrag},
              {'element':document,'type':'mousemove','func':bubble.safariFix},
              {'element':document,'type':'mouseup','func':drag.stop}]);
  bubble.selectT(index);
};

bubble.moveDrag = function(e) {
  var x = mouse.x - drag.x; // left
  if (x < bubble.clip.x1) { x = bubble.clip.x1; }
  if (x+parseInt(drag.obj.style.width) > bubble.clip.x2) { x = bubble.clip.x2-parseInt(drag.obj.style.width); }
  drag.obj.style.left = x + "px";
  var y = mouse.y - drag.y; // top
  if (y < bubble.clip.y1) { y = bubble.clip.y1; }
  if (y+parseInt(drag.obj.style.height) > bubble.clip.y2) { y = bubble.clip.y2-parseInt(drag.obj.style.height); }
  drag.obj.style.top  = y + "px";
};

bubble.downChangesize = function(index,direction) {
  changesize.start({'obj':$('bubbleText_'+index),'direction':direction},
                   [{'element':document,'type':'mousemove','func':bubble.moveChangesize},
                    {'element':document,'type':'mousemove','func':bubble.safariFix},
                    {'element':document,'type':'mouseup','func':changesize.stop}]);
  bubble.selectT(index);
};

bubble.moveChangesize = function(e) {
  var x = mouse.x - changesize.x // width;
  if (x < 10) { x = 10; }
  if (parseInt(changesize.obj.style.left)+x > bubble.clip.x2) { x = bubble.clip.x2-parseInt(changesize.obj.style.left); }
  if ((changesize.direction & 1) == 1) {//lr
    changesize.obj.style.width = x + 'px';
    changesize.obj.childNodes[0].style.width = x + 'px';
    changesize.obj.childNodes[1].style.width = (x - 4) + 'px';
    changesize.obj.childNodes[3].style.width = (x - 4) + 'px';
  }
  y = mouse.y - changesize.y // height;
  if (y < 30) { y = 30; }
  if (parseInt(changesize.obj.style.top)+y > bubble.clip.y2) { y = bubble.clip.y2-parseInt(changesize.obj.style.top); }
  if ((changesize.direction & 2) == 2) {//bt
    changesize.obj.style.height = y + 'px';
    changesize.obj.childNodes[1].style.height = (y - 24) + 'px';
    changesize.obj.childNodes[2].style.height = (y - 24) + 'px';
  }
};

bubble.safariFix = function(e) {
  var o;
  if (crossBrowser.is_safari && ((drag.obj != null) || (changesize.obj != null))) {
    if (drag.obj != null) { o = drag.obj; } else { o = changesize.obj; }
    o.childNodes[1].style.height = o.childNodes[2].style.height;
    o.childNodes[1].style.width = o.childNodes[3].style.width;
  }
};

bubble.mouseSelect = function (e) {
  var o;
  e = e || window.event;
  o = e.target || e.srcElement;
  if (o && o.id && (o.id.substring(0,4)=='text')) {
    bubble.selectT(parseInt(o.id.substr(4)));
  }
};

bubble.toHex = function (n,l) {
  var s,i;
  s = '';
  while (l>0) {
    i = n % 16;
    s = bubble.toHex.digit[i]+s;
    n = (n-i)/16;
    l--;
  }
  return s;
};
bubble.toHex.digit = new Array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');

bubble.selectT = function (i) {
  var e,r,g,b;
  if (i != bubble.selected) {
    if ($('colorWindow')) { bubble.colorWindowHide(); }
    if ($('bubbleText_'+bubble.selected)) {
      $('bubbleText_'+bubble.selected).childNodes[0].style.backgroundColor = bubble.normalColor;
      $('bubbleText_'+bubble.selected).childNodes[2].style.backgroundColor = bubble.normalColor;
      $('bubbleText_'+bubble.selected).childNodes[3].style.backgroundColor = bubble.normalColor;
      $('bubbleText_'+bubble.selected).childNodes[4].style.backgroundColor = 'transparent';
      $('edge'+bubble.selected).childNodes[0].style.backgroundColor = bubble.normalColor;
      $('edge'+bubble.selected).childNodes[1].style.backgroundColor = bubble.normalColor;
    }
    bubble.selected = i;
    if ($('bubbleText_'+bubble.selected)) {
      $('bubbleText_'+bubble.selected).childNodes[0].style.backgroundColor = bubble.selectedColor;
      $('bubbleText_'+bubble.selected).childNodes[2].style.backgroundColor = bubble.selectedColor;
      $('bubbleText_'+bubble.selected).childNodes[3].style.backgroundColor = bubble.selectedColor;
      $('bubbleText_'+bubble.selected).childNodes[4].style.backgroundColor = 'transparent';
      $('edge'+bubble.selected).childNodes[0].style.backgroundColor = bubble.selectedColor;
      $('edge'+bubble.selected).childNodes[1].style.backgroundColor = bubble.selectedColor;
    }
    e = $('font');
    var f = $('tfontid'+bubble.selected).value;
    for (i=0; i<e.options.length; i++) {
      if (f == e.options[i].value) { e.selectedIndex = i; }
    }
    $('fontid').value = $('tfontid'+bubble.selected).value;
    $('fontsize').value = $('tfsize'+bubble.selected).value;
    $('sizeinfo').innerHTML = $('tfsize'+bubble.selected).value;
    bubble.changeAlign($('align'+bubble.selected).value);
    $('color').style.backgroundColor = '#'+bubble.toHex(parseInt($('color'+bubble.selected).value),6);
    $('icolor').value = $('color'+bubble.selected).value;
    $('bgcolor').style.backgroundColor = '#'+bubble.toHex(parseInt($('bgcolor'+bubble.selected).value),6);
    $('ibgcolor').value = $('bgcolor'+bubble.selected).value;
    $('transparent').checked = (parseInt($('transparent'+bubble.selected).value) == 1);
  }
};

bubble.changeAlignIcon = function (align,state) {
  var e,s;
  e = $('align_'+align);
  s = e.childNodes[0].src;
  s = s.substring(0,s.length-5)+((state==align)?'1':'0')+s.substring(s.length-4,s.length);
  e.childNodes[0].src = s;
};

bubble.changeAlign = function (align) {
  if ($('bubbleText_'+bubble.selected)) {
    $('bubbleText_'+bubble.selected).childNodes[1].style.textAlign = align;
    $('align'+bubble.selected).value = align;
  }
  bubble.changeAlignIcon('left',align);
  bubble.changeAlignIcon('center',align);
  bubble.changeAlignIcon('right',align);
  bubble.changeAlignIcon('justify',align);
};

bubble.changeFont = function (f) {
  $('fontid').value = f;
  if ($('bubbleText_'+bubble.selected)) {
    $('bubbleText_'+bubble.selected).childNodes[1].style.fontFamily = bubble.font[f];
    $('tfontid'+bubble.selected).value = f;
  }
};

bubble.changeFontSize = function (s) {
  $('fontsize').value = s;
  $('sizeinfo').innerHTML = s;
  if ($('bubbleText_'+bubble.selected)) {
    $('bubbleText_'+bubble.selected).childNodes[1].style.fontSize = s+'px';
    $('tfsize'+bubble.selected).value = s;
  }
};

bubble.nextSize = function () {
  var i = parseInt($('fontsize').value);
  if (i < 30) { i++; };
  bubble.changeFontSize(i);
};

bubble.prevSize = function () {
  var i = parseInt($('fontsize').value);
  if (i > 10) { i--; };
  bubble.changeFontSize(i);
};

bubble.colorSelected = 'color';

bubble.applyColor = function (c) {
  if (bubble.colorSelected == 'color') {
    $('icolor').value = c;
    $('color').style.backgroundColor = '#'+bubble.toHex(c,6);
    if ($('bubbleText_'+bubble.selected)) {
      $('color'+bubble.selected).value = c;
      $('text'+bubble.selected).style.color = '#'+bubble.toHex(c,6);
    }
  } else {
    $('ibgcolor').value = c;
    $('bgcolor').style.backgroundColor = '#'+bubble.toHex(c,6);
    if ($('bubbleText_'+bubble.selected)) {
      $('bgcolor'+bubble.selected).value = c;
      $('text'+bubble.selected).style.backgroundColor =
        (parseInt($('transparent'+bubble.selected).value) == 1) ? 'transparent' : '#'+bubble.toHex(c,6);
    }
  }
};

bubble.changeColor = function () {
  bubble.colorSelected = 'color';
  colorWindow.show(parseInt($('icolor').value),'bubble.applyColor','#B6C2D8',bubble.rgbtextApply,bubble.rgbtextCancel);
};

bubble.changeBgColor = function () {
  bubble.colorSelected = 'bgcolor';
  colorWindow.show(parseInt($('ibgcolor').value),'bubble.applyColor','#B6C2D8',bubble.rgbtextApply,bubble.rgbtextCancel);
};

bubble.changeTransparent = function () {
  if ($('bubbleText_'+bubble.selected)) {
    $('transparent'+bubble.selected).value = $('transparent').checked ? '1' : '0';
    $('text'+bubble.selected).style.backgroundColor =
      (parseInt($('transparent'+bubble.selected).value) == 1) ? 'transparent' : '#'+bubble.toHex(parseInt($('bgcolor'+bubble.selected).value),6);
  }
}

bubble.newT = function () {
  bubble.addT(0,0,104,104,'',parseInt($('fontid').value),parseInt($('fontsize').value),'left',
              parseInt($('icolor').value),parseInt($('ibgcolor').value),0,true);
};

bubble.addT = function (l,t,w,h,text,fontid,fontsize,align,color,bgcolor,transparent,view) {
  domHelpers.addElement($('bubbleForm'),'div',{'id':'bubbleText_'+bubble.index},{});
  $('bubbleText_'+bubble.index).style.position = 'absolute';
  $('bubbleText_'+bubble.index).style.left = ''+(l+bubble.clip.x1)+'px';
  $('bubbleText_'+bubble.index).style.top = ''+(t+bubble.clip.y1)+'px';
  $('bubbleText_'+bubble.index).style.width = ''+w+'px';
  $('bubbleText_'+bubble.index).style.height = ''+h+'px';
  crossBrowser.addEvent($('bubbleText_'+bubble.index),'mousedown',bubble.mouseSelect);
  var d = '';
  d += "<div class='bubble_dragger' style=\"height:20px; width:"+w+"px\" onmousedown=\"bubble.downDrag('"+bubble.index+"');\"><a href=\"javascript:void(domHelpers.delElement('bubbleText_"+bubble.index+"'));\">[X]</a></div>";
  d += "<textarea style=\"text-align:"+align+"; color:#"+bubble.toHex(color,6)+"; background-color:"+((transparent==1)?"transparent":"#"+bubble.toHex(bgcolor,6))+"; height:"+(h-24)+"px; width:"+(w-4)+"px; font-family:"+bubble.font[fontid]+"; font-size:"+fontsize+"px\" id=\"text"+bubble.index+"\" name=\"text["+bubble.index+"]\" cols='0' rows='0' class='bubbleTextArea'>"+text+"</textarea>";
  d += "<div style=\"height:"+(h-24)+"px; width:4px; font-size: 1px; line-height:1px;\" class='bubble_resize_r' onmousedown=\"bubble.downChangesize('"+bubble.index+"',1);\">&nbsp;</div>";
  d += "<div style=\"height:4px; width:"+(w-4)+"px; font-size: 1px; line-height:1px;\" class='bubble_resize_b' onmousedown=\"bubble.downChangesize('"+bubble.index+"',2);\">&nbsp;</div>";
  d += "<div id='edge"+bubble.index+"' style=\"height:4px; width:4px; font-size: 1px; line-height:1px;\" background-color:transparent; class='bubble_resize_br' onmousedown=\"bubble.downChangesize('"+bubble.index+"',3);\">&nbsp;</div>";
  d += "<input id='top"+bubble.index+"' type='hidden' name='top["+bubble.index+"]' value='' />";
  d += "<input id='left"+bubble.index+"' type='hidden' name='left["+bubble.index+"]' value='' />";
  d += "<input id='width"+bubble.index+"' type='hidden' name='width["+bubble.index+"]' value='' />";
  d += "<input id='height"+bubble.index+"' type='hidden' name='height["+bubble.index+"]' value='' />";
  d += "<input id='tfontid"+bubble.index+"' type='hidden' name='tfontid["+bubble.index+"]' value='"+fontid+"'' />";
  d += "<input id='tfsize"+bubble.index+"' type='hidden' name='tfsize["+bubble.index+"]' value='"+fontsize+"'' />";
  d += "<input id='align"+bubble.index+"' type='hidden' name='align["+bubble.index+"]' value='"+align+"'' />";
  d += "<input id='color"+bubble.index+"' type='hidden' name='color["+bubble.index+"]' value='"+color+"'' />";
  d += "<input id='bgcolor"+bubble.index+"' type='hidden' name='bgcolor["+bubble.index+"]' value='"+bgcolor+"'' />";
  d += "<input id='transparent"+bubble.index+"' type='hidden' name='transparent["+bubble.index+"]' value='"+transparent+"'' />";
  $('bubbleText_'+bubble.index).innerHTML = d;
  d = "<div style=\"height:2px; width:3px; font-size: 1px; line-height:1px; float:left; background-color:"+bubble.normalColor+"\">&nbsp;</div>";
  d += "<div style=\"height:1px; width:2px; font-size: 1px; line-height:1px; float:left; background-color:"+bubble.normalColor+"\">&nbsp;</div>";
  $('edge'+bubble.index).innerHTML = d;
  bubble.selectT(bubble.index);
  bubble.index++;
  if (!view) { bubble.toggleCommand(view); }
};

bubble.reset = function() {
  if ($('colorWindow')) { bubble.colorWindowHide(); }
  for (var i = 0; i < bubble.index; i++) {
    domHelpers.delElement('bubbleText_'+i);
  }
  bubble.index = 0;
};

bubble.toggleCommand = function (text1,text2) {
  bubble.state = !bubble.state;
  $('cmdframe').value = (bubble.state) ? text1 : text2;
  $('cmdframe').title = (bubble.state) ? text1 : text2;
  $('cmdframe').alt = (bubble.state) ? text1 : text2;
  if (bubble.state) {
    for (var i = 0; i < bubble.index; i++) {
      if ($('bubbleText_'+i)) {
        $('bubbleText_'+i).childNodes[0].style.visibility = 'visible';
        $('bubbleText_'+i).childNodes[2].style.visibility = 'visible';
        $('bubbleText_'+i).childNodes[3].style.visibility = 'visible';
        $('bubbleText_'+i).childNodes[4].style.visibility = 'visible';
      }
    }
  } else {
    for (var i = 0; i < bubble.index; i++) {
      if ($('bubbleText_'+i)) {
        $('bubbleText_'+i).childNodes[0].style.visibility = 'hidden';
        $('bubbleText_'+i).childNodes[2].style.visibility = 'hidden';
        $('bubbleText_'+i).childNodes[3].style.visibility = 'hidden';
        $('bubbleText_'+i).childNodes[4].style.visibility = 'hidden';
      }
    }
  }
};

bubble.prepareSend = function (msg) {
  var e;
  var c = 0;
  $('imageid').value = bubble.imageid;
  $('bubbleid').value = bubble.bubbleid;
  for (var i = 0; i < bubble.index; i++) {
    if ($('bubbleText_'+i)) {
      $('top'+i).value = parseInt($('bubbleText_'+i).style.top)-bubble.clip.y1;
      $('left'+i).value = parseInt($('bubbleText_'+i).style.left)-bubble.clip.x1;
      $('width'+i).value = parseInt($('bubbleText_'+i).style.width);
      $('height'+i).value = parseInt($('bubbleText_'+i).style.height);
      $('align'+i).value = $('text'+i).style.textAlign;
      if ($('text'+i).value != '') { c++; }
    }
  }
  if (c == 0) { alert(msg); }
  return (c > 0);
};



function relocateBubbles (dx,dy) {
  var i,o,e;
  o = $('bubbleDiv');
  i = 1;
  while (e = $('bubbleText_'+i) ) {
    l = parseInt(e.style.left) + dx + o.offsetLeft;
    t = parseInt(e.style.top) + dy + o.offsetTop;
    e.style.left = ''+l+'px';
    e.style.top = ''+t+'px';
    i++;
  }
}

bubble_index = 0;

function bubble_toHex (n,l) {
  var s,i;
  s = '';
  while (l>0) {
    i = n % 16;
    s = bubble_toHex.digit[i]+s;
    n = (n-i)/16;
    l--;
  }
  return s;
}
bubble_toHex.digit = new Array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');

function showBubble (id,l,t,w,h,text,font,fontsize,align,color,bgcolor,transparent) {
  var e,o,left,i;
  e = $(id);
  bubble_index++;
  domHelpers.addElement(e,'div',{'id':'bubbleText_'+bubble_index},{});
  o = $('bubbleText_'+bubble_index);  
  o.style.position = 'absolute';
  i = 0; 
  while (e.childNodes[i].nodeName != 'IMG') { i++; } // Workaround Firefox Bug (#TEXT vor IMG)
  left = e.offsetParent.offsetWidth-e.childNodes[i].offsetWidth;
  left = (left - left % 2) / 2;
  if (crossBrowser.is_ie6) { // Workaround für IE6
    o.style.left = ''+(l)+'px';
  } else { // IE7, Firefox, Opera,...
    o.style.left = ''+(l+left-e.offsetLeft)+'px';
  }
  o.style.top = ''+t+'px';
  o.style.width = ''+(w-4)+'px';
  o.style.height = ''+(h-24)+'px';
  o.style.fontFamily = font;
  o.style.fontSize = ''+fontsize+'px';
  o.style.textAlign = align;
  o.style.color = '#'+bubble_toHex(color,6);
  o.style.backgroundColor = (transparent==1) ? 'transparent' : '#'+bubble_toHex(bgcolor,6);
  o.innerHTML = text;
}



var chat = new Object();
chat.chatroom = 0;
chat.stop = false;
chat.duration = 0;
chat.period = 8000;
chat.chatid = 0;
chat.stack = new Array();
chat.msg = function() {
  if (chat.timeout) { clearTimeout(chat.timeout); }
  if (!ajax.activeCall && ($('chat_msg').value != '')) {
    ajax.doRequest('/calls/chatAjax.php?action=new&chatroom='+chat.chatroom+'&msg='+encodeURIComponent($('chat_msg').value),false);
    $('chat_msg').value = '';
  }
  chat.refresh();
};
chat.show = function() {
  while (chat.newstack.length > 0) {
    chat.stack.push(chat.newstack.pop());
  }
  while (chat.stack.length > 50) {
    chat.stack.shift();
  }
  var s = '';
  var i = 0;
  while (i < chat.stack.length) {
    s += '<div class="comm_chat_entry"><span class="comm_chat_avatar"><a class="a_img" href="/artists/'+chat.stack[i][3]+'_'+chat.stack[i][2]+'"><img src="/user/'+chat.stack[i][2]+'/avatar/avatarK.jpg" title="'+chat.stack[i][3]+'\'s profile" /></a></span><div class="comm_chat_contentbox"><span class="comm_chat_copytext">'+chat.stack[i][4]+'</span><span class="comm_chat_userinfo">'+chat.stack[i][3]+' <span class="small">'+chat.stack[i][1]+'</span></span></div><div style="clear:both"></div></div>';
    i++;
  }
  if (i == 0) { chat.chatid = 0; } else { chat.chatid = chat.stack[i-1][0]; }
  if (chat.stop) {
    s += '<div style="margin-top:2px;">Chat stopped.</div>';
  }
  var o = $('chat_div');
  var scroll = (o.innerHTML == '') || (o.scrollTop+300 >= o.scrollHeight);
  o.innerHTML = s;
  if (scroll) {
    setTimeout(chat.scroll,20);
  }
};
chat.scroll = function() {
  var o = $('chat_div'); 
  o.scrollTop = o.scrollHeight;
};
chat.refresh = function() {
  if (ajax.activeCall) {
    setTimeout(chat.refresh,100);
  } else {
    ajax.doRequest('/calls/chatAjax.php?action=refresh&chatroom='+chat.chatroom+'&chatid='+chat.chatid,false);
    if (!chat.stop) {
      chat.timeout = setTimeout(chat.refresh,chat.period);
    }
  }
};
chat.finish = function() {
  chat.stop = true;
  o = $('chat_div');
  var scroll = (o.innerHTML == '') || (o.scrollTop+300 >= o.scrollHeight);
  o.innerHTML += '<div style="margin-top:2px;">Chat stopped.</div>';
  if (scroll) {
    setTimeout(chat.scroll,20);
  }
};
chat.key13 = function() {
  if ($('chat_msg')) {
    crossBrowser.addEvent($('chat_msg'),'keyup',function(e){ if (e.keyCode == 13) { chat.msg(); }});
  }
};



uploadProgress = {};
uploadProgress.keys = {};
uploadProgress.timer = null;
uploadProgress.interval = 2000;
uploadProgress.multiplier = 2;

uploadProgress.add = function(parentid, key) {
  var keyid = 'upload_progress_'+key;
  uploadProgress.keys[key] = {'parentid':parentid, 'keyid':keyid};

  domHelpers.addElement($(parentid),'div',{'id':keyid},[]);
  $(keyid).className = 'upload_progress';
  $(parentid).backgroundColor = '#D0D0E0';

  uploadProgress.update(keyid, 0, 0);

  uploadProgress.start();
};

uploadProgress.start = function() {
  if (uploadProgress.timer == null) {
    uploadProgress.timer = window.setTimeout(uploadProgress.check, uploadProgress.interval);
  }
};

uploadProgress.check = function() {
  var q = [];
  for (var key in uploadProgress.keys) {
    q.push('keys[]='+key);
  }
  ajax.doRequest('/calls/newpicAjax.php?'+q.join('&'),false);
};

uploadProgress.update = function(keyid, percent, timeleft) {
  var html = '';
  html += '<div class="upload_percent" style="width: '+(Math.round(percent)*uploadProgress.multiplier)+'px;"></div>';
  html += '<div class="upload_text">'+Math.round(percent).toString()+'%</div>';
  $(keyid).innerHTML = html;
};

uploadProgress.callback = function(data) {
  var counter = 0;
  for (var key in data) {
    counter++;
    if (uploadProgress.keys[key]) {
      uploadProgress.update(uploadProgress.keys[key].keyid, data[key]['percent'], data[key]['timeleft']);
      if (data[key]['percent'] == 100) {
        delete data[key];
        counter--;
      }
    }
  }

  if (counter > 0) {
    uploadProgress.timer = window.setTimeout(uploadProgress.check, uploadProgress.interval);
  } else {
    uploadProgress.timer = null;
  }
};


// moreOfThisUser (motu)

motu = new Object();
motu.cartoons = new Array();
motu.maxdisp = 4;
motu.maxload = 16;
motu.container = 'motu_container';

motu.next = function () {
  motu.show(motu.index+motu.maxdisp);
};

motu.prev = function () {
  motu.show(motu.index-motu.maxdisp);
};

motu.show = function (pos) {
  var maxdisp,thumbs;
  if (pos > motu.cartoons.length-motu.maxdisp) { pos = motu.cartoons.length-motu.maxdisp; }
  if (pos < 0) { pos = 0; }
  if ((pos > motu.cartoons.length-motu.maxload) && (motu.maxlen > motu.cartoons.length) && (!ajax.activeCall)) {
    ajax.doRequest('/edition/calls/motuAjax.php?imageid='+motu.imageid+'&userid='+motu.userid+'&offset='+motu.cartoons.length+'&cache='+motu.maxload,false);
  }
  if (motu.index != pos) {
    motu.index = pos;
    if (pos+motu.maxdisp > motu.cartoons.length) { 
      maxdisp = motu.cartoons.length-pos;
    } else { 
      maxdisp = motu.maxdisp; 
    }
    thumbs = '';
    for ( ; maxdisp > 0; maxdisp--, pos++) {
      thumbs += motu.printThumb(motu.cartoons[pos]);
    }
    $(motu.container).innerHTML = thumbs;
    $('motu_prev').style.display = (motu.index > 0) ? '' : 'none';
    $('motu_next').style.display = (motu.index+motu.maxdisp < motu.maxlen) ? '' : 'none';
  }
};

motu.printThumb = function (c) {
  return '<div class="thumb"><div class="thumb_pic"><a class="a_img" href="/edition/buyimage?imageid='+
         c['imageid']+'&amp;title='+c['title']+'"><img class="thumb_img" style="margin-top:'+
         c['top']+'px; width:'+c['thumb_x']+'px; height:'+c['thumb_y']+'px;" title="'+
         decodeURIComponent(c['title'])+'" alt="'+decodeURIComponent(c['title'])+'" src="/user/'+c['userid']+
         '/thumbs/'+c['imageuid']+'.jpg" /></a>'+'</div><div style="font-size:10px; padding:5px;"><b>'+
         decodeURIComponent(c['title_short'])+'</b><br /></div></div>';
};



