/*
 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
 * Digest Algorithm, as defined in RFC 1321.
 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for more info.
 */

/*
 * 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_md5(s){return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
function b64_md5(s){return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
function str_md5(s){return binl2str(core_md5(str2binl(s), s.length * chrsz));}
function hex_hmac_md5(key, data) {return binl2hex(core_hmac_md5(key, data));}
function b64_hmac_md5(key, data) {return binl2b64(core_hmac_md5(key, data));}
function str_hmac_md5(key, data) {return binl2str(core_hmac_md5(key, data));}

/*
 * Perform a simple self-test to see if the VM is working
 */
function md5_vm_test()
{
  return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}

/*
 * Calculate the MD5 of an array of little-endian words, and a bit length
 */
function core_md5(x, len)
{
  /* append padding */
  x[len >> 5] |= 0x80 << ((len) % 32);
  x[(((len + 64) >>> 9) << 4) + 14] = len;

  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;

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

    a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
    d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
    c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
    b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
    a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
    d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
    c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
    b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
    a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
    d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
    c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
    b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
    a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
    d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
    c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
    b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);

    a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
    d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
    c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
    b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
    a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
    d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
    c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
    b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
    a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
    d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
    c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
    b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
    a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
    d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
    c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
    b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);

    a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
    d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
    c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
    b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
    a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
    d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
    c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
    b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
    a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
    d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
    c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
    b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
    a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
    d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
    c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
    b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);

    a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
    d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
    c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
    b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
    a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
    d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
    c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
    b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
    a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
    d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
    c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
    b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
    a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
    d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
    c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
    b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);

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

}

/*
 * These functions implement the four basic operations the algorithm uses.
 */
function md5_cmn(q, a, b, x, s, t)
{
  return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
  return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
  return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
  return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
  return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}

/*
 * Calculate the HMAC-MD5, of a key and some data
 */
function core_hmac_md5(key, data)
{
  var bkey = str2binl(key);
  if(bkey.length > 16) bkey = core_md5(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_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
  return core_md5(opad.concat(hash), 512 + 128);
}

/*
 * 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 bit_rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}

/*
 * Convert a string to an array of little-endian words
 * If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
 */
function str2binl(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) << (i%32);
  return bin;
}

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

/*
 * Convert an array of little-endian words to a hex string.
 */
function binl2hex(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] >> ((i%4)*8+4)) & 0xF) +
           hex_tab.charAt((binarray[i>>2] >> ((i%4)*8  )) & 0xF);
  }
  return str;
}

/*
 * Convert an array of little-endian words to a base-64 string
 */
function binl2b64(binarray)
{
  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i += 3)
  {
    var triplet = (((binarray[i   >> 2] >> 8 * ( i   %4)) & 0xFF) << 16)
                | (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
                |  ((binarray[i+2 >> 2] >> 8 * ((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;
}

/*	SWFObject v2.2 <http://code.google.com/p/swfobject/>
	is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();

/**
 * Element.Storage for Prototype 1.6, is included in Prototype 1.7
 *
 * Added by ChristophH, 2010/10/27
 * 
 * from http://www.prototypejs.org/2009/2/16/pimp-my-code-1-element-storage,
 * required by text change events
 */
if (Prototype.Version < "1.7") {
	Element.Storage = {
		UID: 1
	};
	
	Element.addMethods({
		getStorage: function(element) {
			if (!(element = $(element))) return;

			if (Object.isUndefined(element._prototypeUID))
				element._prototypeUID = Element.Storage.UID++;

			var uid = element._prototypeUID;

			if (!Element.Storage[uid])
				Element.Storage[uid] = $H();

			return Element.Storage[uid];
		},

		store: function(element, key, value) {
			if (!(element = $(element))) return;
			element.getStorage().set(key, value);
			return element;
		},

		retrieve: function(element, key, defaultValue) {
			if (!(element = $(element))) return;

			var hash = element.getStorage(), value = hash.get(key);

			if (Object.isUndefined(value)) {
				hash.set(key, defaultValue);
				value = defaultValue;
			}

			return value;
		}
	});
}

/**
 * JS for site wide notifications, for example notifications about new features
 * Author: Christoph Hochstrasser
 */
Event.observe(document, "click", function(e) {
	var element = e.findElement("#notifications a[data-close]");

	if(!element) return;

	var href = element.readAttribute("href");

	var app  = new Weblife1.AjaxApp([
		new Weblife1.AjaxApp.Component.Data({id: element.up(".box_dynamic").readAttribute("id")})
	], "close_notification");

	app.doProcess();

	element.up(".box_dynamic").remove();

	if (href) {
		document.location = href;
	} else {
		e.stop();
	}
});

var Weblife1Nav = {

	hideClass			: 'hidemenu',
	showClass			: 'showmenu',

	menuHover			: 'selected',
	subMenuContainer	: 'navigation_sub',

	defaultSubmenu		: null,
	defaultMenu			: null,

	lastSubmenu			: null,
	lastMenu			: null,

	mouseX				: 0,
	mouseY				: 0,

	backSwitch			: null,

	show : function(element, defaultSubmenu, defaultMenu)
	{
		element = $(element);

		if(!element) {
			return false;
		}

		if(Weblife1Nav.backSwitch)
		{
			Weblife1Nav.backSwitch.stop();
			Weblife1Nav.backSwitch = null;
		}

		Weblife1Nav.defaultSubmenu	= $(defaultSubmenu).id;
		Weblife1Nav.defaultMenu		= $(defaultMenu).id;

		if(!Weblife1Nav.defaultSubmenu ||
			!Weblife1Nav.defaultMenu)
		{
			Weblife1Nav.defaultSubmenu	= null;
			Weblife1Nav.defaultMenu		= null;
		}
		else if(!Weblife1Nav.lastSubmenu)
		{
			Weblife1Nav.lastSubmenu = Weblife1Nav.defaultSubmenu;
		}

		var subElement = $(element.readAttribute('rel'));

		if(!subElement) {
			return false;
		}

		if(Weblife1Nav.lastSubmenu)
		{
			$(Weblife1Nav.lastSubmenu).addClassName(Weblife1Nav.hideClass);
			$(Weblife1Nav.lastSubmenu).removeClassName(Weblife1Nav.showClass);
		}

		if(Weblife1Nav.lastMenu)
		{
			$(Weblife1Nav.lastMenu).removeClassName(Weblife1Nav.menuHover);
		}

		if(Weblife1Nav.defaultMenu != element.id)
		{
			element.addClassName(Weblife1Nav.menuHover);
			Weblife1Nav.lastMenu = element.id;
		}

		Weblife1Nav.lastSubmenu = subElement.id;

		subElement.addClassName(Weblife1Nav.showClass);
		subElement.removeClassName(Weblife1Nav.hideClass);

		Weblife1Nav.backSwitch = new PeriodicalExecuter(Weblife1Nav.reset, 1);
	},

	getMouseInfo : function(e)
	{
		if(!e)
		{
			e = window.event;
			if(!e)
			{
				return;
			}
		}

		Weblife1Nav.mouseX = Event.pointerX(e);
		Weblife1Nav.mouseY = Event.pointerY(e);
	},

	reset : function(pe)
	{
		if(Weblife1Nav.lastMenu &&
			Weblife1Nav.lastSubmenu &&
			Weblife1Nav.defaultSubmenu)
		{
			Position.cumulativeOffset($(Weblife1Nav.lastMenu));
			Position.cumulativeOffset($(Weblife1Nav.lastSubmenu));

			if(Position.within($(Weblife1Nav.lastMenu), Weblife1Nav.mouseX, Weblife1Nav.mouseY) ||
				Position.within($(Weblife1Nav.subMenuContainer), Weblife1Nav.mouseX, Weblife1Nav.mouseY))
			{
				return;
			}
			$(Weblife1Nav.lastMenu).removeClassName(Weblife1Nav.menuHover);
			Weblife1Nav.lastMenu = null;

			$(Weblife1Nav.lastSubmenu).addClassName(Weblife1Nav.hideClass);
			$(Weblife1Nav.lastSubmenu).removeClassName(Weblife1Nav.showClass);
			Weblife1Nav.lastSubmenu = null;

			$(Weblife1Nav.defaultSubmenu).addClassName(Weblife1Nav.showClass);
			$(Weblife1Nav.defaultSubmenu).removeClassName(Weblife1Nav.hideClass);

			Weblife1Nav.backSwitch.stop();
			Weblife1Nav.backSwitch = null;
		}
		else
		{
			Weblife1Nav.backSwitch.stop();
			Weblife1Nav.backSwitch = null;
		}
	}
}


document.onmousemove = Weblife1Nav.getMouseInfo;

/* Weblife1 Panel + SkyThird TopPosition add */
function toggleDiv(currentElm, elm2hide,elm3pos, elm4pos){
		var e = $(elm2hide);
        var p = $(elm3pos);/*sky*/
        var b = $(elm4pos);/*bigsize*/
		var s = $(currentElm).down('small');

        if(p != null)
        {
        	var pTop = p.getStyle('top'); /*sky*/
        	pTop = parseInt(pTop.substr(0, pTop.length - 2));
        }
        if(b != null)
        {
        	var bTop = b.getStyle('top'); /*bigsize*/
        	bTop = parseInt(bTop.substr(0, bTop.length - 2));
        }


		if(e.getStyle('display') != 'none')
		{
			 e.setStyle({'display' : 'none'});
			 if(p != null)
			 {
				 p.setStyle({'top' : eval(pTop - 206) + 'px'});
			 }
			 if(b != null)
		     {
				 b.setStyle({'top' : eval(bTop - 206) + 'px'});
		     }
			 s.update('&#9660;');
		}
		else
		{
			 e.setStyle({'display' : 'block'});
			 if(p != null)
			 {
				 p.setStyle({'top' : eval(pTop + 206) + 'px'});
			 }
			 if(b != null)
		     {
				 b.setStyle({'top' : eval(bTop + 206) + 'px'});
		     }
			 s.update('&#9650;');
		}

}
/**
 * FRIENDS_CHAT
**/
//template
var tString = '<div id="#{mid}">' +
					'<span class="username">#{from}</span>' +
					'<span class="timestamp floatRight">#{date}</span>'+
					'</div><div class="messagebody" id="message_#{mid}">#{content}</div>';


var peers = new Hash();
var peerIds = new Hash();
var friendlist;
var widgets = new Array();
widgets = $A(widgets);
var me;
var _stream_channel;
var _videochat_w_width = '340'; //-210
var _videochat_w_height = '545'; //-135
var _videochat_w_urlparams = '&namespace=Szene1&adoverlaytime=20&adoverlaytext=Verbindungsaufbau ...';
//var chatPosCookie = new Szene1.Cookies();

var Chat = Class.create({

	initialize: function(myid, soPeer) {
		this.soPeer = soPeer;
		this.visible = false;
		this.owner  = myid;
		this.histLoaded = false;
	   this.myWindowHasFocus = true;
	   this.oldTitle = window.document.title;
		this.panel = this.soPeer ? $('chatWidgetSO') : $('chatPanel');
	   this.titlePex = null;
	   this.aniCount = 0;
	   me = this.owner;
		this.widgets = new Hash();
//		this.initState = false;
		this.soundNewMessage = '/sound/newm_frcht.mp3';
		this.init();
		this.isMaster = false;
		this.lastPeer = '';
		this.channel = _stream_channel = new SChannel(this);
		Event.observe(window, 'blur', this.handleWindowBlur.bindAsEventListener(this));
		Event.observe(window, 'focus', this.handleWindowFocus.bindAsEventListener(this));
		Event.observe(document.body, 'on:titleChanged', this.handleTitleChanged.bindAsEventListener(this));
	},

	init: function() {
		var panel =  '';
		if(!this.soPeer) {
			panel +=  '<div id="chatBoxTitle" class="box_title">';
			panel += '<div class="box_titleBody"><h3 style="display:inline">Friends-Talk</h3><span style="color:#999;"><b>&nbsp;&nbsp;cam-chat</b> beta-test</span>';
			panel += '</div>';
			panel += '<div class="icon_container">';
//			panel += '<span class="box_icon close10red_btn" id="chatwindowclosebtn">&nbsp;</span>';
			panel += '<span class="box_icon ICON16_BW_MOVE">&nbsp;</span>';
			panel += '</div></div>';
			panel += '<div style="width:100%;text-align:center;">';
			panel += '<a class="bigLink" href="/site/anleitung_friends_talk">Talks in der Online-Friendlist starten</a>';
			panel += '</div>';
		}
		panel += '<div id="niftyplayer" style="position:absolute;top:-333px;" ><p>&nbsp;</p></div>';

      this.panel.innerHTML = panel;
		var flashvars = {};
		var params = {allowScriptAccess:"always"};
		var attributes = {id: "niftyplayer1", name:"niftyplayer1", movie:"/flash/fxplayer.swf?file=/sound/newm_frcht.mp3"};
		swfobject.embedSWF(	"/flash/fxplayer.swf?file=/sound/newm_frcht.mp3",
									"niftyplayer","1","1","9.0.0", "",
									flashvars, params, attributes);
//		var so = new SWFObject("/flash/fxplayer.swf?file=/sound/newm_frcht.mp3",
//										"niftyPlayer1", "1", "1", "8");
//		so.addParam("id", "niftyPlayer1");
//		so.addParam("allowScriptAccess","always");
//		so.write("niftyPlayer");
		if(!this.soPeer) {
//			Event.observe('chatwindowclosebtn', 'click', this.handleChatWindowClose.bindAsEventListener(this));
			var pos = getCookieChatPos();
			if(pos) {
				this.panel.style.top = pos.top;
				this.panel.style.left = pos.left;
			}
			new Draggable(this.panel, {handle:"chatBoxTitle", snap:constrainSnap, onEnd:setChatPosCookie});
			// get show-state of chat window
	//		var ftState = parseInt(getCookieChatState());
	//		console.log(ftState);
	//		if(ftState != 0) {
	//			console.log('state of window: ' + ftState);
		}
//		this.show();
//		}

	},

	show: function() {
		setChatStateCookie('1');
		this.panel.style.zIndex = '999';
		this.visible = true;
	},

	hide: function() {
//		this.histLoaded = false;
		this.panel.style.zIndex = '-1';
		this.visible = false;
	},

	master: function(bool) {
		this.isMaster = bool;
	},

	handleTitleChanged: function(e) {
//		console.log(e);
		this.oldTitle = window.document.title;
	},

	handleWindowBlur: function(t) {
//		console.log('focus lost');
		this.myWindowHasFocus = false;
		return false;
	},

	handleWindowFocus: function(t) {
//		console.log('focus got');
		this.myWindowHasFocus = true;
		this.stopTitleAni();
		return false;
	},

	handleChatWindowClose : function(e) {
		this.visible = false;
		this.hide();
		setChatStateCookie('0');
	},

	stopTitleAni: function(t) {
		if(this.titlePex != null) {
			try {
				this.titlePex.stop();
				this.titlePex = null;
			}
			catch(e) {}
			}
		window.document.title = this.oldTitle;
		return false;
	},

	startAni: function() {
		if(this.titlePex == null)
		{
			this.titlePex = new PeriodicalExecuter(this.toggleTitle.bind(this),1);
		}
	},

	playSound: function() {
//		alert('play sound ');

		niftyplayer('niftyplayer1').play();
	},

	toggleTitle: function() {
		if((this.aniCount % 2) == 0) {
			window.document.title = 'Nachricht von ' + this.lastPeer;
		}
		else
		{
			window.document.title = this.oldTitle;
		}
		++this.aniCount;
	},

	newMessage: function(event) {
//		console.log('send a message...');
		this.channel.postRequest(event.memo.text, event.memo.cwid, false);
		Event.stop(event);
		return false;
	},

	handleNewMessage: function(message) {
		if(this.soPeer && (peers.get(message.ct_id) != this.soPeer) ) {
			return false;
		}
		var thePeer = (message.s_id == me) ? 'undefined' : message.s_id;
		var widgetId = parseInt(message.ct_id);
		var wid = this.getWidget(widgetId, thePeer);
		wid.appendMessage(message);
		this.lastPeer = message.s_id;
		if((message.s_id != me) && this.isMaster) {
			if(!this.myWindowHasFocus) {
				this.startAni();
			}
			if(this.histLoaded && this.visible)
			{
				this.playSound();
			}
		}
		return false;
	},

	handleCamChatInvite: function(message) {
		var widgetId = parseInt(message.ct_id);
		var thePeer = (message.s_id == me) ? 'undefined' : message.s_id;
		var wid = this.getWidget(widgetId, thePeer);
		var url = "/videochat/?streamout="+me+"&streamin="+wid.peer+_videochat_w_urlparams;
		var name = "videochat with " + wid.peer;
		message.mess = '<a title="Start Video-Chat" onclick="showVChatPopup(\''+url+'\', \''+name+'\');return false;"  href="#"><span class="ICON16_BW_VIDEO2">&nbsp;</span><span>Einladung zum VideoChat mit <strong>'+message.s_id+'</strong> annehmen.</span></a>';
		wid.appendMessage(message);
	},

	handleStateMessage: function(message) {
//		console.log(message);return;
		if(this.soPeer && (message.peer != this.soPeer) ) {
//			alert('standalone mode!');
			return false;
		}
//		alert('new state message');

		var csid = parseInt(message.ct_id);
		var newState = parseInt(message.state);

		if (newState == 0) {
			if (typeof this.widgets.get(csid) != 'undefined') {
//			console.log(csid );

				$('chatPanel').removeChild($(this.widgets.get(csid).widgetId));
				this.widgets.unset(csid);
			}
			if(this.widgets.size() < 1)
			{
				this.hide();
			}
		}
		else {
			if(this.visible) {
				this.show();
			}
			if (message.peer != '0' && message.peer != 'undefined') {
				peers.set(csid, message.peer);
			}
			var peerState = parseInt(message.pstate);
			var unread = parseInt(message.unrd);

			var wid = this.getWidget(csid, peers.get(csid));
			wid.setState(newState);
			wid.setUnread(unread);
			wid.setPeerState(peerState);
		}
		return false;
	},

	handlePeerStateMessage: function(message) {
		var csid = parseInt(message.ct_id);
		var peerState = parseInt(message.pstate);
		var wid = this.getWidget(csid);
		wid.setPeerState(peerState);
	},

	updateWidgets: function() {
		this.widgets.each(function(widget) {
			widget.value.update(this.histLoaded);
		}.bind(this));
	},

	getWidget: function(widgetId, peer) {
		if(typeof peer == 'undefined') {
			peer = peers.get(widgetId);
		}
		if(typeof this.widgets.get(widgetId) != 'undefined') {
			var myWidget = this.widgets.get(widgetId);
			if(typeof myWidget.peer == 'undefined' && (typeof peer != 'undefined')) {
				myWidget.setPeer(peer);
			}
			return myWidget;
		}
		else{
			var widget = new ChatWidget(widgetId, peer, (this.soPeer == peer));
			this.widgets.set(widgetId, widget);
			widget.render();
			Event.observe($(widget.widgetId), 'on:widgetStateChange', this.handleWidgetState.bindAsEventListener(this));
			Event.observe($(widget.widgetId), 'focus', this.stopTitleAni.bindAsEventListener(this));
			Event.observe($(widget.widgetId), 'on:newChatMessage', this.newMessage.bindAsEventListener(this));
			this.show();
			return widget;
		}
	},

	getWidgetId: function(elementId) {
		return elementId.split('_').first();
	},

	handleWidgetState: function(e) {
		//alert(e.eventName);
		var widget = Event.element(e);
//		console.log("indicate busy");
		var id = this.getWidgetId(widget.id);
		var widgetObject = this.widgets.get(id);
		widgetObject.indicateBusy();
		var state;
		state = widgetObject.getState();
		var message = {
		 	'sessionid': id,
		 	'state': state,
		 	'peer': me, // userid,
			'error' : 0,
			'type' : 'chat_stateupdate'
	   };
		//alert(Object.toQueryString(message));
		this.channel.postUpdateState(Object.toQueryString(message));
	},


	createChat: function(name) {
//		console.log('new chat with ' + name + ' - ' + id);
//		peerIds.set(name, id);
		return this.channel.newChatWindow(name);
	},

	callBackNewWidget: function(response) {
//		console.log("callBackNewWidget called with response: " +response);
		return this.getWidget(response.created);
	}



}); // class Chat

function setChatPosCookie(element, event) {
	element = element.element;
	//console.log('set cookie to top: ' + element.style.top + ' - left: ' + element.style.left);
	var wert = element.style.top+':' + element.style.left;
	setChatCookie('chatpos', wert);
}

function setChatCookie(name, value) {

	var cook = name + "=" + unescape(value);
    cook += "; domain=" + window.location.hostname;
    var expires = new Date();
    var expiresDiff = expires.getTime() + (30 * 24 * 60 * 60 * 1000);
    expires.setTime(expiresDiff);

    cook += "; expires="+expires.toGMTString();;
    cook += "; path=/";
    document.cookie = cook;
}

function setChatStateCookie(value) {
	setChatCookie('chatstate', value);
}

function getCookieChatPos() {
//	console.log(document.cookie);
	var cook = readCookie('chatpos');
	if(cook != null) {
		cook = cook.split(':');
		return {top:cook[0], left:cook[1]};
	}
	return false;
}

function getCookieChatState() {
//	console.log(document.cookie);
	var cook = readCookie('chatstate');
	if(cook != null) {
//		cook = cook.split(':');
		return cook;
	}
	return false;
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function showVChatPopup(url, name) {
			var popup = window.open(url, null, "width="+_videochat_w_width+",height="+_videochat_w_height+",scrollbars=1,resizable=0,menubar=no,location=no,status=no");
			popup.focus();
		}

/**
 * channel-communication **************************************************************************************
 */
var SChannel = Class.create();
SChannel.prototype = {

	initialize: function(handler){
		//this.channels = channels;
		this.iframeSrc = streamChannelSrc + me;
		this.stream = null;
		this.handler = handler;
		this.createChannel();

		// test div
		this.notificationContainer = document.createElement('div');
		this.notificationContainer.id = 'as_not_container';
		this.notificationContainer.style.display = 'none';
		this.notificationContainer.style.position = 'fixed';
		this.notificationContainer.style.bottom = '0px';
		this.notificationContainer.style.left = '985px';
		//this.notificationContainer.style.width = '330px';
		//this.notificationContainer.style.height = '25px';
		this.notificationContainer.style.border = '1px solid #B61312';
		this.notificationContainer.style.background = 'white';
		var html = '<div id="as_not_cont" class="box_dynamic chat_widget" style="width:330px;">';
		html += '<div id="as_not_cont_head" class="widget_head clearfix" style="width:330px;">';
		html += '<div class="widget_thumb">';
//		html += '<a title="userpage v muhadib" class="szene1_status_thumb" href="/user/muhadib">';
		html += '<span>';
		html += '<img id="notContUserPic" border="0" alt="" src="">';
//		html += '</span></a>';
		html += '</div>';
		html += '<div class="widget_title"><h3>Neue Aktvität</h3>';
//		html += '<span><em class="online"> online</em></span>';
		html += '</div>';
		html += '<div class="widget_icon floatRight">';
		html += '<span id="as_not_cont_close" class="box_icon close10red_btn" title="close">&nbsp;</span>';
		html += '<span class="widget_counter_new floatRight" title="neue nachrichten" style="display: none;" id="cnt_new_1283867949459953"></span>';
		html += '<span class="widget_icon floatRight"></a></span>';
		html += '</div></div>';
		html += '<div id="as_not_ch_widget_body" class="widget_body" style="width:330px;">';
		html += 'CONTENT';
		html += '</div>';

		html += '</div>';
		this.notificationContainer.innerHTML = html;
		document.body.appendChild(this.notificationContainer);
		Event.observe($('as_not_cont_close'), 'click', this.notContainerHide.bindAsEventListener(this));
		this.notContBody = $('as_not_ch_widget_body');
		this.notTimeOut = null;
	},
	
	notContainerHide: function() {
		this.notificationContainer.style.display = 'none';
	},

	createChannel: function() {

		var iframe = document.createElement('iframe');
		iframe.frameborder = 0;
		iframe.src = this.iframeSrc;
		iframe.id = 'app_channel';
		iframe.width=1;
		iframe.height=1;
		iframe.style.display = 'none';
		document.body.appendChild(iframe);
		this.stream = iframe.contentWindow;
	},

	responseCallback: function(response){
		response.each(function(object){
			switch (object.type) {
				case "ct_mess":
//					console.log("got message: ");
					this.handler.handleNewMessage(object.data);
					break;
				case "ct_state":
//					alert('ct_state');
					this.handler.handleStateMessage(object.data);
					break;
				case "ct_pstate":
//					console.log("got peer_state: ");
					this.handler.handlePeerStateMessage(object.data);
					break;
				case "ct_vchat":
//					alert('chat invitation!!!');
//					console.log("ct_vchat");
					this.handler.handleCamChatInvite(object.data);
					break;
				case "as_not":
					this.showNotification(object.data);
			}

		}.bind(this));
		this.handler.updateWidgets();
		this.handler.histLoaded = true;
	},


	buildNotificationBodyContainer: function(message) {

	},
	showNotification: function(message) {
		message = message.evalJSON();
		$('notContUserPic').src = message.picURL;
		this.notificationContainer.appear({duration: .5});
		this.notContBody.innerHTML = message.txt;
		this.notificationContainer.highlight();
		var fade = function() {
			this.notificationContainer.fade({duration: .4});
		}.bind(this);
//		alert('hey!!');
		Publisher.doThisToo(message);
		this.notTimeOut = window.setTimeout(fade, 30000);
		this.notContainerHide();
	},

	sigMaster: function(master){
		this.handler.master(master);
	},

	postRequest: function(message, csid, url){
		this.stream.postRequest(message, csid, url);
		return false;
	},

	sendPost: function(data, url) {
		this.stream.postRequest(url, param, data);
	},

	postUpdateState: function(message) {
	//	console.log("post state update: "+message);
		this.stream.postUpdateRequest(message, false);
		return false;
	},

	newChatWindow: function(peer) {
		this.stream.requestChatId(peer, me);
		return false;
	}
}//Channel

/**
 * lib
 */
function getDate(timestamp) {
	var day = new Date();
	day.setTime((timestamp) * 1000);
	var out = leadingZero(day.getUTCDate()) + '.' +
				leadingZero(day.getUTCMonth()+1) + ' um ' +
				leadingZero(day.getUTCHours()) + ':' +
				leadingZero(day.getUTCMinutes());
	return out;
}

function leadingZero(string) {
	string = ""+string;
	return string.length == 1 ? '0' + string : string;
}

/************************* widget ******************************/
var smiley_array =  ['%3A%29','%3B%28', '%3B%29', '%3AD'];
var smiley_xhtml =  ['smile','traurig','zwinker', 'grins'];

function linkify(text){
        text = text.replace(/((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/ig,
            function(url){
                var full_url = url;
                if (!full_url.match('^https?:\/\/')) {
                    full_url = 'http://' + full_url;
                }
                return '<a href="' + full_url + '" target="_blank">' + url + '</a>';
            }
        );
    return smiley(text);
}

function  smiley(text)
{
text = escape(text);
 for (var i = 0; i< smiley_array.length; i++)
 {
//  var word = smiley_array[i].replace(')','\\)');
  var word = new RegExp(smiley_array[i], 'gi');
  var smiley_img = '<img src="/images/smilies/smile_' + smiley_xhtml[i] + '.gif" />';
  text = text.replace(word, smiley_img);
 }
 return unescape(text);
}


/**
 * @author heyoka
 */
var ChatWidget = Class.create();

ChatWidget.prototype = {
	initialize: function(sessionid, peer, isStandalone) {
	this.id  = sessionid;
	this.peer = peer;
	this.isStandalone = isStandalone;
	this.peerState = 0;
	this.state = 0;
	this.hasUnread = 0;
//	this.element = $();
	this.lastElement = null;
	this.textInput = null;
	this.pStateInd = null;
	this.element = null;
	this.counterNew = null;
	this.widgetId = this.id + "_ch_widget";
  	},

	appendMessage: function(message) {
		var t = new Template(tString);
		var ele = document.createElement('div');
		ele.className = "message";
		ele.id = 'm_' + message.mess_id;
		if(message.mess_id == '0') {
			ele.title = 'no_message';
		}
		var fromSpan = (message.s_id == me) ? me : '<strong>'+message.s_id+'</strong>';
		ele.innerHTML = t.evaluate( {from 	: fromSpan,
												date 	: getDate(message.date),
												mid 	: message.mess_id,
												content: linkify(message.mess)}
											);
		$(this.widgetId + '_printarea').appendChild(ele);
		if(message.s_id != me) {
			this.lastElement = ele;
		}
	},

	setUnread: function(count) {
		this.hasUnread = count;
	},

	setPeerState: function(state) {
		this.peerState = state;
	},

	setPeer: function(newPeer) {
		this.peer = newPeer;
		document.removeChild($(this.widgetId()));
		this.render();
	},

	setState: function(newState) {
//		console.log("new State for widget: " + this.id + ' -> ' + newState);
		this.state = newState;
		switch(newState) {
			case 0:
				this.hide();
				break;
			case 1:
				this.compact();
				break;
			case 2:
				this.open();
				break;
		}

	},

	getState: function() {
		return this.state;
	},

	update :function(loaded) {
//		console.log('update ' + this.id + ' with histLoaded: ' + loaded);
		var area = $(this.widgetId+'_printarea');
		area.scrollTop = area.scrollHeight + 200;
	  // indicator update
	  if (this.hasUnread > 0) {
		this.indicateNewMessage();
	 }
	 else {
	 	this.resetIndicator();
	 }
	 if(this.peerState == 1) {
//	 	console.log("show peer online");
	 	this.showPeerOnline();
	 }
	 else {
//	 	console.log("show peer offline");
		this.showPeerOffline();
	 }
	 $(this.widgetId).setOpacity(1);
	 if(this.lastElement && loaded) {
	 	new Effect.Highlight(this.lastElement, {duration:0.8});
	 }
     this.lastElement = null;
	},

	widgetId: function() {
		return this.id + "_ch_widget";
	},

	indicateNewMessage: function() {
		$(this.widgetId).className = 'box_dynamic chat_widget widget_head_new';
		this.counterNew.style.display = '';
		this.counterNew.innerHTML = this.hasUnread;
	},

	resetIndicator: function() {
		$(this.widgetId).className = 'box_dynamic chat_widget';
		this.counterNew.style.display = 'none';
		this.counterNew.innerHTML = '';
	},

	indicateBusy: function() {
//		console.log("busy");
		$(this.widgetId).setOpacity(0.5);

	},


	showPeerOnline: function() {
		this.pStateInd.innerHTML = '<em class="online"> online</em>';
	},
	showPeerOffline: function() {
		this.pStateInd.innerHTML = '<em class="offline"> offline</em>';
	},

	// make the widget small // only the headerbox is visible
	toggleCompact: function(newState) {
		Event.stop(newState);
		var ele = Event.element(newState).up('a');
//		console.log(ele);
		if(ele && (ele.className == 'szene1_status_thumb')) {
			window.location.href = ele.href;
			return false;
		}
		if (this.state == 1) {
			this.state = 2;
//		 	this.open();
		}
		else {
			this.state = 1;
//			this.compact();
		}
		Event.fire($(this.widgetId),'on:widgetStateChange');
		return false;
	},

	getBodyElement: function() {
		return $(this.widgetId + '_body');
	},

	open: function() {
		this.show();
		this.getBodyElement().style.display = '';

	},

	compact: function() {
		this.getBodyElement().style.display = 'none';
	},

	hide: function() {
		$(this.widgetId).style.display = 'none';
	},

	show: function() {
		$(this.widgetId).style.display = '';

	},

	closing: function(e) {
		Event.stop(e);
//		this.hide();
		this.state = 0;
		Event.fire($(this.widgetId),'on:widgetStateChange');
		return false;
	},

   startVideoChat: function(event) {
      Event.stop(event);
		var url = "/videochat/?streamout="+me+"&streamin="+this.peer+_videochat_w_urlparams;
		var name = "videochat with " + this.peer;
		var popup = window.open(url, null,"width="+_videochat_w_width+",height="+_videochat_w_height+",scrollbars=1,resizable=0,menubar=no,location=no,status=no");
    	popup.focus();
		// now send chat invitation
		var inviteUrl = $('app_channel').contentWindow.fullDomain + "/chatinvite/" + me;
		//console.log("inviteUrl = " + inviteUrl);
		$('app_channel').contentWindow.postRequest("", this.id, inviteUrl);
		return false;
   },

	render: function() {
		var that = this;
		// the widget
		var widget = document.createElement('div');
		widget.id = this.widgetId;
		widget.className = 'box_dynamic chat_widget';
		/**
		 * HEADER
		 */
		if(!this.isStandalone) {
			var header = document.createElement('div');
			header.id = this.id + '_head';
			header.className = 'widget_head clearfix';
			widget.appendChild(header);

			/**
			 * thumb
			 */
			var thumb = document.createElement('div');
			thumb.className = 'widget_thumb';
			thumb.innerHTML = '<a href="/user/'+this.peer+'" class="szene1_status_thumb" title="userpage v '+this.peer+'"><span><img border="0" src="/xhr/userpic.php?name='+this.peer+'" alt="" /></span></a>'
			header.appendChild(thumb);

			var title = document.createElement('div');
			title.id = this.id + '_chat_title';
			title.innerHTML = '<h3>' + this.peer+ '</h3>';
			title.className = 'widget_title';

			this.pStateInd = document.createElement('span');
			this.pStateInd.innerHTML = '<em class="online"> online</em>';
	//		this.pStateInd.className = 'online';
	//		this.pStateInd.innerHTML = ' online';
			title.appendChild(this.pStateInd);

			header.appendChild(title);

			var vChatButton = document.createElement('span');
			vChatButton.className = 'widget_icon floatRight';
			vChatButton.innerHTML = '<a title="Start Video-Chat" class="ICON16_BW_VIDEO2 icon floatRight" href="#"></a>';
			Event.observe(vChatButton, 'click', this.startVideoChat.bindAsEventListener(this));

			var tools = document.createElement('div');
			tools.className = 'widget_icon floatRight';
			var toogle = document.createElement('span');
			toogle.title = 'minimieren / maximieren';
			toogle.className = 'box_icon dash10red_btn';
			toogle.innerHTML = '&nbsp;';

			Event.observe(header, 'click', this.toggleCompact.bindAsEventListener(this));

			var closeButton = document.createElement('span');
			closeButton.rel = this.id;
			closeButton.className = 'box_icon close10red_btn';
			closeButton.title = 'close';
			closeButton.innerHTML = '&nbsp;';
			Event.observe(closeButton, 'click', this.closing.bindAsEventListener(this));

			this.counterNew = document.createElement('span');
			this.counterNew.className = 'widget_counter_new floatRight';
			this.counterNew.title = 'neue nachrichten';
			this.counterNew.style.display = 'none';
			this.counterNew.id = 'cnt_new_'+this.id;

			tools.appendChild(closeButton);
			tools.appendChild(toogle);
			header.appendChild(tools);
			tools.appendChild(this.counterNew);
			tools.appendChild(vChatButton);
		}
		/**
		 * body
		 */
		var line = document.createElement('div');
		line.className = 'dottedline';
		line.innerHTML = '&nbsp;';

		// bodyarea
		var body = document.createElement('div');
		body.id = this.widgetId + '_body';
		body.className = 'widget_body';
		widget.appendChild(body);
		// the printarea
		var paid = this.widgetId + '_printarea';
		var printarea = document.createElement('div');
		printarea.id = paid;
		printarea.className = 'printarea';

		body.appendChild(line);
		body.appendChild(printarea);

		//input field
		var sendForm = document.createElement('div');
		sendForm.className = 'widget_send box_form';
		body.appendChild(sendForm);

		this.textInput = document.createElement('input');
		this.textInput.id = this.widgetId + '_input';
		this.textInput.type = 'text';
		this.textInput.name = this.textInput.id + '_name';
		this.textInput.style.width = '175px';
		// add to widget
		sendForm.appendChild(this.textInput);
		var sendButton = document.createElement('a');
		sendButton.className = 'form_btn red';
		sendButton.innerHTML = 'Send';
		sendButton.id = this.id + '_send';

		sendForm.appendChild(sendButton);
//		$('chatPanel').appendChild(widget);
		theChat.panel.appendChild(widget);
		// now listen to the keyboard ;)
		Event.observe(this.textInput, 'keypress', this.sendMessage.bindAsEventListener(this));
		Event.observe(sendButton,'click', this.sendMessage.bindAsEventListener(this));
		this.state = 2; // open
		return widget;
	},

	sendMessage: function(event) {
		var textToSend;
		if(	(event.keyCode == Event.KEY_RETURN) ||
			(Event.element(event).id == this.id+'_send')) {
			Event.stop(event);

		   	textToSend = trim($F(this.textInput));
			if(textToSend) {
				$(this.widgetId).fire('on:newChatMessage', {text:textToSend, cwid: this.id});
//				postRequest(textToSend, this.id, false);
			}
			this.textInput.value = '';
		}
		return false;
	}


};//class

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function constrainSnap(x, y, draggable) {

function constrain(n, lower, upper) {if (n > upper) {return upper;} else if (n < lower) {return lower;} else {return n;}}

var draggableElement = draggable.element;var elementDimensions = Element.getDimensions(draggableElement);var parentDimensions = Element.getDimensions(document.body);
var vpDim = document.viewport.getDimensions();
return [constrain(x, 0, parentDimensions.width - elementDimensions.width), constrain(y, 0, vpDim.height- elementDimensions.height)];}//



// Script for NiftyPlayer 1.7, by tvst from varal.org - modified by heyoka from szene1.at
// Released under the MIT License: http://www.opensource.org/licenses/mit-license.php

var FlashHelper =
{
	movieIsLoaded : function (theMovie)
	{
		if (typeof(theMovie) != "undefined") {
			return theMovie.PercentLoaded() == 100;
		}
		else {
			return false;
		}
  },

	getMovie : function (movieName)
	{
		if (navigator.appName.indexOf ("Microsoft") !=-1) {
			return window[movieName];
		}
		else {
			return document[movieName];
		}
	}
};

function niftyplayer(name)
{
	this.obj = FlashHelper.getMovie(name);

//	if (!FlashHelper.movieIsLoaded(this.obj)) return;

	this.play = function () {
//		alert('play the sound jonny !');
		if(this.obj) // crome does not find the player-object
		{
			this.obj.TCallLabel('/','play');
		}
	};

	this.stop = function () {
		this.obj.TCallLabel('/','stop');
	};

	this.pause = function () {
		this.obj.TCallLabel('/','pause');
	};

	this.playToggle = function () {
		this.obj.TCallLabel('/','playToggle');
	};

	this.reset = function () {
		this.obj.TCallLabel('/','reset');
	};

	this.load = function (url) {
		this.obj.SetVariable('currentSong', url);
		this.obj.TCallLabel('/','load');
	};

	this.loadAndPlay = function (url) {
		this.load(url);
		this.play();
	};

	this.getState = function () {
		var ps = this.obj.GetVariable('playingState');
		var ls = this.obj.GetVariable('loadingState');

		// returns
		//   'empty' if no file is loaded
		//   'loading' if file is loading
		//   'playing' if user has pressed play AND file has loaded
		//   'stopped' if not empty and file is stopped
		//   'paused' if file is paused
		//   'finished' if file has finished playing
		//   'error' if an error occurred
		if (ps == 'playing')
			if (ls == 'loaded') return ps;
			else return ls;

		if (ps == 'stopped')
			if (ls == 'empty') return ls;
			if (ls == 'error') return ls;
			else return ps;

		return ps;

	};

	this.getPlayingState = function () {
		// returns 'playing', 'paused', 'stopped' or 'finished'
		return this.obj.GetVariable('playingState');
	};

	this.getLoadingState = function () {
		// returns 'empty', 'loading', 'loaded' or 'error'
		return this.obj.GetVariable('loadingState');
	};

	this.registerEvent = function (eventName, action) {
		// eventName is a string with one of the following values: onPlay, onStop, onPause, onError, onSongOver, onBufferingComplete, onBufferingStarted
		// action is a string with the javascript code to run.
		//
		// example: niftyplayer('niftyPlayer1').registerEvent('onPlay', 'alert("playing!")');

		this.obj.SetVariable(eventName, action);
	};

	return this;

}

var UserFacelist = Class.create({
	checked: $A(),
	defaultOptions: {
		groups:                ".groups",
		friends:               ".friends",
		actions:               ".actions",
		selectedClass:         "selected",
		visibleClass:          "visible",
		disabledClass:         "ui-disabled",
		actionSelectAllClass:  ".select-all em",
		actionSelectNoneClass: ".select-nothing em"
	},

	initialize: function(element, options) {
		this.options = Object.extend(this.defaultOptions, options);
		this.element = $(element);
		this._initTranslations();
		this._initDOMReferences();
		this._initEventHandlers();
	},

	setOptions: function(options) {
		this.options = Object.extend(this.options, options);
	},

	getOptions: function() {
		return this.options;
	},

	getSelected: function() {
		data = $A();

		for(var i = 0, len = this.checked.length; i < len; ++i) {
			data[i] = $F(this.checked[i]);
		}

		return data;
	},

	clearSelected: function() {
		this.checked = this.checked.clear();
	},

	disable: function() {
		this.element.addClassName(this.options.disabledClass);
		this.friends.stopObserving("click", this.friendSelectHandler);
		this.friends.stopObserving("click", this.groupSelectHandler);
		this.actions.stopObserving("click", this.actionHandler);
	},

	enable: function() {
		this.element.removeClassName(this.options.disabledClass);
		this._initEventHandlers();
	},

	_handleFriendSelect: function(e) {
		e.stop();
		var target   = e.findElement("li");
		var checkbox = target.toggleClassName(this.options.selectedClass)
		               .down("input[type=checkbox]");

		if (checkbox.checked) {
        	checkbox.checked = false;
        	this.checked = this.checked.without(checkbox);
        } else {
        	checkbox.checked = true;
        	this.checked.push(checkbox);
        }

        this._markAction();
	},

	_handleGroupSelect: function(e) {
		e.stop();
		var link = e.findElement("a");

		if(!link) {
			return;
		}

		this.groups.down("a." + this.options.selectedClass)
		.removeClassName(this.options.selectedClass);

		link.addClassName(this.options.selectedClass);

		var fragment = link.readAttribute("href").match(/#[A-Za-z0-9\-_]+/).first();

		if(fragment == "#all-friends") {
			var actionSelectAllTitle  = this.translations.selectAll;
			var actionSelectNoneTitle = this.translations.selectNothing;

			this.friends.childElements().each(function(li) {
				li.setStyle({display: "block"}).addClassName(this.options.visibleClass);
			}.bind(this));
		} else {
			var actionSelectAllTitle  = this.translations.allFromGroup + ": " + link.textContent;
			var actionSelectNoneTitle = this.translations.noneFromGroup + ": " + link.textContent;

			this.friends.select(".group." + this.options.visibleClass).each(function(el) {
				el.hide().removeClassName(this.options.visibleClass);
			}.bind(this));

			this.friends.select(fragment).first().show().addClassName(this.options.visibleClass);
		}
		this.actions.down(this.options.actionSelectAllClass).update(actionSelectAllTitle);
		this.actions.down(this.options.actionSelectNoneClass).update(actionSelectNoneTitle);
	},

	_handleActions: function(e) {
		e.stop();
		var li = e.findElement("li");

		if (!li) {
			return;
		}

		var action = li.hasClassName("select-all") ? "select-all" : "select-none";
		var selectedGroup = this.groups.select("a." + this.options.selectedClass)[0];
		var fragment = selectedGroup.readAttribute("href").match(/#[A-Za-z0-9\-_]+/).first();

		if(fragment != "#all-friends") {
			var checkboxes = this.friends.select(fragment + " input[type=checkbox]");
		} else {
			var checkboxes = this.friends.select("input[type=checkbox]");
		}

		for(var i = 0, len = checkboxes.length; i < len; ++i) {
			checkboxes[i].checked = (action == "select-all") ? true : false;

			if (action == "select-all") {
				this.checked[i] = checkboxes[i];
				checkboxes[i].up().addClassName(this.options.selectedClass);
			} else {
				this.checked = this.checked.clear();
				checkboxes[i].up().removeClassName(this.options.selectedClass);
			}
		}
		this._markAction();
	},

	_markAction: function() {
		var selected = this.actions.down("a." + this.options.selectedClass);

		if(selected) {
			selected.removeClassName(this.options.selectedClass);
		}

    	if (this.checked.length == 0) {
    		this.actions.down(".select-nothing a").addClassName(this.options.selectedClass);

    	} else if (this.friends.select("input[type=checkbox]").length == this.checked.length) {
    		this.actions.down(".select-all a").addClassName(this.options.selectedClass);
    	}
	},

	_initDOMReferences: function() {
		this.groups  = this.element.down(this.options.groups);
		this.friends = this.element.down(this.options.friends);
		this.actions = this.element.down(this.options.actions);

		this.groups.down("li:first-child a").addClassName(this.options.selectedClass);
	},

	_initEventHandlers: function() {
		this.friendSelectHandler = this._handleFriendSelect.bindAsEventListener(this);
		this.groupSelectHandler  = this._handleGroupSelect.bindAsEventListener(this);
		this.actionHandler       = this._handleActions.bindAsEventListener(this);

		this.friends.observe("click", this.friendSelectHandler);
		this.groups.observe("click",  this.groupSelectHandler);
		this.actions.observe("click", this.actionHandler);
	},

	_initTranslations: function() {
		this.translations = {
			selectAll:     Szene1Translator.translate("all"),
			selectNothing: Szene1Translator.translate("statusPermNobody"),
			allFromGroup:  Szene1Translator.translate("allFromGroup"),
			noneFromGroup: Szene1Translator.translate("noneFromGroup")
		};
	}
});

/**
 * Port of jQuery textchange plugin to prototype, for detecting
 * text changes in text fields and editable elements
 * 
 * Original jQuery plugin: http://www.zurb.com/playground/jquery-text-change-custom-event
 * Author: Christoph Hochstrasser <c.hochstrasser@szene1.at>
 */
 
/**
 * fires text:change, text:notext, text:hastext
 */
(function() {
	
	Event.observe(document, "keyup", textchangeHandler);
	Event.observe(document, "cut",   delayedHandler);
	Event.observe(document, "paste", delayedHandler);
	
	function textchangeHandler(event) {
		triggerIfChanged(event.element());
	}
	
	function delayedHandler(event) {
		// New field value is not instantly available on cut/paste event -> wait
		(function() {
			triggerIfChanged(event.element());
		}).defer();
	}
	
	function triggerIfChanged(element) {
		element = Element.extend(element);	
		
		if (!element.match("textarea") && !element.match("input") 
			&& !element.match("*[contenteditable]")) {
			return;
		}
		
		var current = element.readAttribute("contenteditable") 
			? element.innerHTML 
			: element.getValue();
		
		if (current !== element.retrieve("lastValue", " ")) {
			Event.fire(element, "text:change", current);
			element.store("lastValue", current);
		}
	}
	
	/** 
	 * Convenience wrappers for listening to text change events
	 */
	function hasText(element, callbackFn) {
		Event.observe(element, "text:hastext", callbackFn);
	}
	
	function noText(element, callbackFn) {	
		Event.observe(element, "text:notext", callbackFn);
	}
	
	function textChange(element, callbackFn) {
		Event.observe(element, "text:change", callbackFn);
	}
	
	Event.observe(document, "text:change", function(event) {
		var lastValue = event.element().retrieve("lastValue");
		
		// Return if value has not changed
		if (lastValue === event.element().getValue()) return;
		
		if (event.element().getValue() === "") {
			Event.fire(event.element(), "text:notext", event.memo);
		} else if ((lastValue === '') || (lastValue === ' ')) {
			Event.fire(event.element(), "text:hastext", event.memo);
		}
	});
	
	// Add some convenience methods for listening to textchange events,
	// Note: not available on "contenteditable" elements
	Element.addMethods(["INPUT", "TEXTAREA"], {
		"hasText":    hasText,
		"noText":     noText,
		"textChange": textChange
	});
})();

/**
 * Simple Class for doing JSONP Requests, partially inspired by jQuery's ajax() and
 * a gist by Tobie Langel at http://gist.github.com/145466
 *
 * JSONP (JSON with Padding) is a simple method for doing
 * cross domain Javascript HTTP requests.
 * Need for oEmbed compatible APIs, can also be used for requests to Facebook's Graph API
 * Also see http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/
 *
 * Author: Christoph Hochstrasser <c.hochstrasser@szene1.at>
 */
Object.extend(Ajax, function() {
	var count  = 0,
		rurl   = /^(\w+:)?\/\/([^\/?#]+)/,
		jsre   = /\=\?(&|$)/,
	    rquery = /\?/,
	    head   = $$("head")[0];
	
	var JSONP = Class.create({
		initialize: function(url, parameters, callbackFn) {
			var url   = url || document.location,
				jsonp = "jsonp" + count++,
				script;
			
			var callbackParam = $H(parameters).unset("callbackParameter") || "callback";
			
			// Hash of parameters given
			if (typeof parameters === "object") {
				parameters = $H(Object.clone(parameters || {}));
				
				// Attach the callback parameter to the hash
				var c;
				if (c = parameters.index("?")) {
					parameters.set(c, jsonp);
				} else {
					parameters.set(callbackParam, jsonp);
				}
				parameters = parameters.toQueryString();
				url += (rquery.test(url) ? "&" : "?") + parameters;
			
			} else {
				// Attach the callback directly to the url if no parameters hash is given
				if (!jsre.test(url)) {
					url += (rquery.test(url) ? "&" : "?") + callbackParam + "=?";
				}
				url = url.replace(jsre, "=" + jsonp + "$1");
			}
			
			// Allow jQuery-like avoidance of parameters hash
			if ((typeof parameters === "function") && (typeof callbackFn === "undefined")) {
				callbackFn = parameters;
			}
			
			window[jsonp] = function(json) {
				script.remove();
				script        = null;
				window[jsonp] = undefined;
				callbackFn(json);
			}
			
			script = new Element("script", {src: url, type: "text/javascript"});
			head.insert(script);
		}
	});
	
	return {
		"JSONP": JSONP
	};
}());

/**
 * oEmbed Client Library for Prototype
 * Author: Christoph Hochstrasser <c.hochstrasser@szene1.at>
 */
var oEmbed = Class.create({
	options: {
		url:   "http://api.embed.ly/v1/api/oembed",
		regex: /http:\/\/(.*youtube\.com\/watch.*|.*\.youtube\.com\/v\/.*|youtu\.be\/.*|.*\.youtube\.com\/user\/.*#.*|.*\.youtube\.com\/.*#.*\/.*|.*justin\.tv\/.*|.*justin\.tv\/.*\/b\/.*|.*\.dailymotion\.com\/video\/.*|.*\.dailymotion\.com\/.*\/video\/.*|www\.collegehumor\.com\/video:.*|vids\.myspace\.com\/index\.cfm\?fuseaction=vids\.individual&videoid.*|www\.myspace\.com\/index\.cfm\?fuseaction=.*&videoid.*|www\.metacafe\.com\/watch\/.*|blip\.tv\/file\/.*|.*\.blip\.tv\/file\/.*|video\.google\.com\/videoplay\?.*|video\.yahoo\.com\/watch\/.*\/.*|video\.yahoo\.com\/network\/.*|.*viddler\.com\/explore\/.*\/videos\/.*|.*yfrog\..*\/.*|www\.flickr\.com\/photos\/.*|flic\.kr\/.*|.*twitpic\.com\/.*|xkcd\.com\/.*|www\.xkcd\.com\/.*|.*dribbble\.com\/shots\/.*|drbl\.in\/.*|.*\.smugmug\.com\/.*|.*\.smugmug\.com\/.*#.*|picasaweb\.google\.com.*\/.*\/.*#.*|picasaweb\.google\.com.*\/lh\/photo\/.*|picasaweb\.google\.com.*\/.*\/.*|www\.facebook\.com\/photo\.php.*|www\.hulu\.com\/watch.*|www\.hulu\.com\/w\/.*|hulu\.com\/watch.*|hulu\.com\/w\/.*|www\.funnyordie\.com\/videos\/.*|www\.vimeo\.com\/groups\/.*\/videos\/.*|www\.vimeo\.com\/.*|vimeo\.com\/groups\/.*\/videos\/.*|vimeo\.com\/.*|movies\.yahoo\.com\/movie\/.*\/video\/.*|movies\.yahoo\.com\/movie\/.*\/info|movies\.yahoo\.com\/movie\/.*\/trailer|www\.theonion\.com\/video\/.*|theonion\.com\/video\/.*|wordpress\.tv\/.*\/.*\/.*\/.*\/|soundcloud\.com\/.*|soundcloud\.com\/.*\/.*|soundcloud\.com\/.*\/sets\/.*|soundcloud\.com\/groups\/.*|www\\.last\\.fm\/music\/.*|www\\.last\\.fm\/music\/+videos\/.*|www\\.last\\.fm\/music\/+images\/.*|www\\.last\\.fm\/music\/.*\/_\/.*|www\\.last\\.fm\/music\/.*\/.*|www\.mixcloud\.com\/.*\/.*\/|.*amazon\..*\/gp\/product\/.*|.*amazon\..*\/.*\/dp\/.*|.*amazon\..*\/dp\/.*|.*amazon\..*\/o\/ASIN\/.*|.*amazon\..*\/gp\/offer-listing\/.*|.*amazon\..*\/.*\/ASIN\/.*|.*amazon\..*\/gp\/product\/images\/.*|www\.amzn\.com\/.*|amzn\.com\/.*|gist\.github\.com\/.*|twitter\.com\/.*\/status\/.*|twitter\.com\/.*\/statuses\/.*|polldaddy\.com\/community\/poll\/.*|polldaddy\.com\/poll\/.*|answers\.polldaddy\.com\/poll\/.*|www\.screencast\.com\/.*\/media\/.*|screencast\.com\/.*\/media\/.*|www\.screencast\.com\/t\/.*|screencast\.com\/t\/.*|tumblr\.com\/.*|.*\.tumblr\.com\/post\/.*|www\.polleverywhere\.com\/polls\/.*|www\.polleverywhere\.com\/multiple_choice_polls\/.*|www\.polleverywhere\.com\/free_text_polls\/.*|.*\.status\.net\/notice\/.*|identi\.ca\/notice\/.*|.*.jpg|.*.gif|.*.png|.*.jpeg)/i
	},
	
	initialize: function(options) {
		Object.extend(this.options, options || {});
	},
	
	replaceElements: function(elements, options) {
		var api     = this.options.url,
			options = Object.extend({
				"urlAttribute":  "href",
				"parameters": {},
				"onRender":   this.getDefaultRenderFn()
			}, options);
		
		// selector given
		if (Object.isString(elements)) {
			elements = $$(elements);
		}
		
		if (elements.length === 0) throw "No elements to replace";
		
		elements.each(function(a) {
			options.parameters.url = a.readAttribute(options.urlAttribute);
			
			new Ajax.JSONP(
				api, 
				options.parameters, 
				function(response) {
					a.insert({after: options.onRender(response)});
					a.remove();
				}
			);
		});
	},
	
	getDefaultRenderFn: function() {
		return(function(response,template) {
			var content;
			
			switch (response.type) {
                                case "photo":
                                        content = new Element("img", {src: response.url});
                                        break;
                                case "rich":
                                case "video":
					if(template)
						content = template.interpolate(response);
					else
	                                        content = response.html;
                                        break;
                                case "error":
                                        content = false;
                                        break;
                                default:
                                        content = response.html;
                                        break;
                        }
                        return content;
		});
	},
	
	matchUrls: function(text) {
		var matches = text.match(this.options.regex);
		return (matches && (matches.length > 0)) ? true : false;
	},
	
	api: function(params, callbackFn) {
		var params = params || {}
		
//		if (params.url.match(this.options.regex) === null) return;
		
		new Ajax.JSONP(this.options.url, params, callbackFn);
	}
});

var Timeline = Class.create({
	options: {
		'type'  : 'subscriber',
		'oType'	: 0,
		'oId'	: 0,
		'offset': 0,
		'limit'	: 10,
		'filter': new Array('\"news\"','\"activity\"','\"notification\"'),
		'relevance': true,
		'geo' : {},
		'community': true,
		'outputType': 1
	},
	initialize: function(options) {
		Object.extend(this.options, options || {});
	},
	getMore : function()
	{
		this.request = new Weblife1.AjaxApp.Setup.Servercall("timelineR", {
				'requesttype': 'get_more',
				'type'  : this.options.type,
				'oType'	: this.options.oType,
				'oId'	: this.options.oId,
				'limit'	: this.options.limit,
				'offset': this.options.offset,
				'filter': this.options.filter,
				'relevance': this.options.relevance,
				'geo' : this.options.geo,
				'community': this.options.community,
				'outputType': this.options.outputType
			}, (function(object){
				if(object['content'] == null) {$('addContent').innerHTML += 'nothing more to see';return;} 
				$('addContent').innerHTML += object['content'];
				this.options.offset = object['offset'];
	        }).bind(this), {
				'defaultContent'	: null,
				'draggable'			: true,
				'sendOnSubmit'		: true
			});
	
	}
});

