// ä

var busy = false;

function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x) {
		curleft += obj.x;
	}
	return curleft;// + document.body.offsetLeft;
}

function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

var jsonUsers = {};

function getUserJSON(userId) {
	if (jsonUsers["user_" + userId] === undefined) {
		jsonUsers["user_" + userId] = null;
		loadUserJSON(userId);
	}
	return jsonUsers["user_" + userId];
}

var jsonUsersLoadQueue = [];
var jsonBusy = false;

function loadUserJSON(userId) {
	jsonUsersLoadQueue.push(userId);
	if (!jsonBusy) {
		jsonBusy = true;
		loadJSONUsers();
	}
}

function loadJSONUsers() {
	ajaxPost("/action/userJSON", {
			userIds: jsonUsersLoadQueue.join(" ")
		},
		function(data){
			if (data == "GOTOLOGIN") {
				window.location.href = "/";
				return;
			}
			var data = data.replace( /\r\n/g, "\n" );
			var splitData = data.split("\n");
	
			if (splitData[0] == "ok") {
				for (var i=1; i<splitData.length; i++) {
					if (splitData[i].length > 0) {
						var jsonObject; eval( "jsonObject = " + splitData[i] );
						// type USER
						var jsonUser;
						if ("object" in jsonObject) {
							jsonUser = jsonObject.object;
							jsonUser.error = false;
						}
						else {
							jsonUser = {error: true};
						}
						if ("karma" in jsonObject) {
							jsonUser["karma"] = jsonObject["karma"];
							jsonUser["karmaString"] = jsonObject["karmaString"];
						}
						if (jsonObject.authUser) {
							jsonUsers["user_0"] = jsonUser;
						}
						else {
							jsonUsers["user_" + jsonUser.userId] = jsonUser;
						}
					}
				}
			}
			if (jsonUsersLoadQueue.length > 0) {
				loadJSONUsers();
			}
			else {
				jsonBusy = false;
			}
		},
		function(){
			if (jsonUsersLoadQueue.length > 0) {
				loadJSONUsers();
			}
			else {
				jsonBusy = false;
			}
		});	
	jsonUsersLoadQueue = []
}
				
var pipeovertimer = null;
var pipeouttimer = null;
var pipeLastPictureId = "0";
var pipeLastUserId = 0;
var pipeXOffset = 0;
var pipeXPositionId = "";
var pipeShowing = false;
var pipeExtraShowing = false;
var pipeposx = 0;
var pipeposy = 0;

function pipemouseover(e, owner, userId, pictureId, xOffset, xPositionId, changeUser) {
	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
	
	var reltg = (e.relatedTarget) ? e.relatedTarget : e.fromElement;
	while (reltg && reltg != owner && reltg.nodeName != 'BODY' && reltg.parentNode)
		reltg= reltg.parentNode;
	if (reltg == owner) return;
	
	if (pipeovertimer == null && !pipeShowing) {
		pipeovertimer = window.setTimeout(pipeovertimertimeout, 300);
	}
	if (pipeouttimer != null) {
		window.clearTimeout(pipeouttimer);
		pipeouttimer = null;
	}
	pipeXOffset = xOffset;
	pipeXPositionId = xPositionId;
	if (changeUser && pipeShowing) {
		var pipepic = document.getElementById("pipefloat");
		if (pipeLastUserId != userId) {
			var modResult = ((pictureId.substring(0, 10) % 6) + pictureId.substring(10)) % 6;
			pipepic.src = "http://static2" + modResult + ".wie-ich.de/up/" + pictureId + "-100.jpg";
			pipeLastPictureId = pictureId;
			pipeLastUserId = userId;
			updatePipeProfile();
		}
		pipepic.style.display = "block";
		document.getElementById("pipefloatmore").style.display = "block";
	}
	if (changeUser || !pipeShowing) {
		pipeLastPictureId = pictureId;
		pipeLastUserId = userId;
		pipePosition(e);
	}
}

function pipemouseoverpipe(e, owner) {
	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
	
	var reltg = (e.relatedTarget) ? e.relatedTarget : e.fromElement;
	while (reltg && reltg != owner && reltg.nodeName != 'BODY' && reltg.parentNode)
		reltg= reltg.parentNode
	if (reltg == owner) return;
	
	if (pipeouttimer != null) {
		window.clearTimeout(pipeouttimer);
		pipeouttimer = null;
		document.getElementById("pipefloatmore").style.display = "block";
		document.getElementById("pipefloatmoreextra").style.display = "block";
		pipeExtraShowing = true;
	}
}

function pipemouseout(e, owner) {
	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
	
	var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
	while (reltg && reltg != owner && reltg.nodeName != 'BODY' && reltg.parentNode)
		reltg= reltg.parentNode
	if (reltg == owner) return;

	if (pipeovertimer != null) {
		window.clearTimeout(pipeovertimer);
		pipeovertimer = null;
	}
	if (pipeShowing && pipeouttimer == null) {
		pipeouttimer = window.setTimeout(pipeouttimertimeout, 200);
	}
}

function pipemousemove(e, owner) {
	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
	
	if (true || targ == owner)	 {
		pipePosition(e);
	}
}

function pipePosition(e) {
	var pipeposx;
	var pipeposy;
	
	if (e.pageX || e.pageY) 	{
		pipeposx = e.pageX;
		pipeposy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		pipeposx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		pipeposy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
	var posel = document.getElementById(pipeXPositionId);
	if (posel) {
		pipeposx = findPosX(document.getElementById(pipeXPositionId));
	}
	document.getElementById("pipefloatmore").style.left = (pipeposx+pipeXOffset) + "px";
	document.getElementById("pipefloatmore").style.top = (pipeposy-40) + "px";
	if (pipeShowing) {
		document.getElementById("pipefloatmore").style.display = "block";
	}
}

function pipeovertimertimeout() {
	var pipepic = document.getElementById("pipefloat");
	var modResult = ((pipeLastPictureId.substring(0, 10) % 6) + pipeLastPictureId.substring(10)) % 6;
	pipepic.src = "http://static2" + modResult + ".wie-ich.de/up/" + pipeLastPictureId + "-100.jpg";
	updatePipeProfile();
	pipepic.style.display = "block";
	document.getElementById("pipefloatmore").style.display = "block";
	pipeShowing = true;
	pipeovertimer = null;
}

function updatePipeProfile() {
	var jsonAuthUser = getUserJSON(0);
	var jsonUser = getUserJSON(pipeLastUserId);
	if (jsonUser != null && jsonAuthUser != null) {
		var outString =  "";
		if ("karma" in jsonUser && jsonUser.karma > 45) {
			outString = outString + "<div title=\"" + jsonUser.karmaString + "\" class=\"linkkarma" + (jsonUser.karma>45?jsonUser.karma>85?jsonUser.karma>160?jsonUser.karma>600?4:3:2:1:0) + "\" style=\"position:absolute;width:16px;height:16px;left:85px;background-color:#fbb\"></div>";
		}
		outString = outString + "<div>" + jsonUser.name + "</div>";
		if (!jsonAuthUser.error && "city" in jsonUser && jsonAuthUser.age >= 25) {
			var mapString = "<div style=\"position:relative;height:34px;margin-top:5px;margin-left:30px\"><img style=\"position:absolute;left:-3px;top:1px\" src=\"/gfx/map32.gif\" width=\"44\" height=\"32\" />";
			if ("city" in jsonAuthUser) {
				mapString = mapString + "<div style=\"position:absolute;width:3px;border-top:3px solid #26F;left:" + 
				Math.round((jsonAuthUser.lon - 5)*3.42 -1 -3) + "px;top:" + Math.round((55-jsonAuthUser.lat)*3.42 -1 +1) +  "px\"></div>";
			}
			mapString = mapString + "<div style=\"position:absolute;width:3px;border-top:3px solid #F00;left:" + 
				Math.round((jsonUser.lon - 5)*3.42 -1 -3) + "px;top:" + Math.round((55-jsonUser.lat)*3.42 -1 +1) +  "px\"></div></div>";
			mapString = mapString + "<div style=\"text-align:center;margin-bottom:5px;height:32px;overflow:hidden;width:98px;overflow:hidden;white-space:nowrap\">" + jsonUser.city;
			if ("region" in jsonUser && jsonUser.region != jsonUser.city) {
				mapString = mapString + "<br />" + jsonUser.region + "";
			}
			mapString = mapString + "</div>";
			outString = outString + mapString;
		}
		if (jsonAuthUser.error || jsonAuthUser.age < 25) {
			outString = outString + "<div class=\"pipepbstatus\">" + jsonUser.pbStatus + "</div>";
		}
		var outStringExtra = "<div id=\"pipeextracontent\">";
		outStringExtra = outStringExtra + "<div id=\"pipeuserstatus\" onmouseover=\"this.style.display='none';document.getElementById('pipeuserstatusfull').style.display='block';\">";
		if ("status" in jsonUser) {
			outStringExtra = outStringExtra + jsonUser.statusAbb;
		}
		outStringExtra = outStringExtra + "</div>";
		outStringExtra = outStringExtra + "<div id=\"pipeuserstatusfull\" style=\"display:none\">";
		if ("status" in jsonUser) {
			outStringExtra = outStringExtra + jsonUser.status;
		}
		outStringExtra = outStringExtra + "</div>";
		outStringExtra = outStringExtra + "</div>";
		document.getElementById("pipefloatmore2").innerHTML = outString;
		document.getElementById("pipefloatmore2").style.visibility = "visible";
		document.getElementById("pipefloatmoreextra").innerHTML = outStringExtra;
		if (!pipeExtraShowing) {
			document.getElementById("pipefloatmoreextra").style.display = "none";
		}
	}
	else {
		document.getElementById("pipefloatmore2").style.visibility = "hidden";
		if (document.getElementById("pipeextracontent")) {
			document.getElementById("pipeextracontent").style.visibility = "hidden";
		}
		window.setTimeout(updatePipeProfile, 50);
	}
}

function pipeouttimertimeout() {
	pipeShowing = false;
	pipeExtraShowing = false;
	var pipepic = document.getElementById("pipefloat");
	pipepic.style.display = "none";
	document.getElementById("pipefloatmore").style.display = "none";
	pipepic.style.visibility = "hidden";
	pipepic.src = null;
	pipeouttimer = null;
}

function pipeloaded(element) {
	element.style.visibility = "visible";
}




var moreovertimer = null;
var moreouttimer = null;
var moreShowing = false;
var moreId = null;

function moremouseover(e, owner, id) {
	if (getWindowHeight() < 750 && document.getElementById("sim_menu_options")) {
		if (document.getElementById("menuclub")) {
			document.getElementById("menumore").className="sim_menu_more sim_menu_more_large_club lighter";
		}
		else {
			document.getElementById("menumore").className="sim_menu_more sim_menu_more_large lighter";
		}
		document.getElementById("menumore_inner").className="sim_menu_more_i sim_menu_more_i_large dark";
	}
	else {
		document.getElementById("menumore").className="sim_menu_more sim_menu_more_small lighter";
		document.getElementById("menumore_inner").className="sim_menu_more_i sim_menu_more_i_small dark";
	}
	moreId = id;
	if (moreovertimer == null) {
		moreovertimer = window.setTimeout(moreovertimertimeout, 100);
	}
	if (moreouttimer != null) {
		window.clearTimeout(moreouttimer);
		moreouttimer = null;
	}
}

function moremouseout(e, owner, id) {
	var eventSource = (window.event) ? e.srcElement : e.target;
	if (e.type == "mouseout" && (eventSource.nodeName == "SELECT" || eventSource.nodeName == "INPUT")) return;
	
	moreId = id;
	if (moreovertimer != null) {
		window.clearTimeout(moreovertimer);
		moreovertimer = null;
	}
	if (moreShowing) {
		moreouttimer = window.setTimeout(moreouttimertimeout, 200);
	}
}

function moreovertimertimeout() {
	if (document.getElementById("menumore") && moreId == "club") {
		document.getElementById("menumore").style.display = "none";
	}
	if (document.getElementById("menuclub") && moreId == "more") {
		document.getElementById("menuclub").style.display = "none";
	}
	var menumore = document.getElementById("menu" + moreId);
	menumore.style.display = "block";
	if (!moreShowing && moreId == "more" && document.getElementById("ftsfld")) {
		document.getElementById("ftsfld").focus();
	}
	moreShowing = true;
	moreovertimer = null;
}

function moreouttimertimeout() {
	moreShowing = false;
	var menumore = document.getElementById("menu" + moreId);
	if (menumore) {
		menumore.style.display = "none";
	}
	moreouttimer = null;
}

function getCookie(name) {
	var cookies = document.cookie.split('; ');
	for (var i=0; i< cookies.length; i++) {
		var c = cookies[i];
		var pos = c.indexOf('=');
		var n = c.substring(0, pos);
		if (n==name) {
			return c.substring(pos+1);
		}
	}
	return null;
}

function startchat(room) {
	window.name = "communitymain";
	var jsessionid = getCookie("JSESSIONID");
	if (jsessionid != null) {
		var newwindow = window.open( '', 'chat', 'width=511,height=383,location=no,menubar=no,resizable=yes,scrollbars=no' );
		if (newwindow.windows == undefined) {
			document.cookie = "SSOJSESSIONID=" + jsessionid + ";domain=wie-ich.de";
			newwindow.location.href="http://chat" + Math.floor(Math.random()*99999000 + 100) + ".wie-ich.de/chat2.jsp" + (room?"?room="+room:"");
		}
		newwindow.focus();
	}
}

function getWindowHeight() {
  if( typeof( window.innerHeight ) == 'number' ) {
	  return window.innerHeight;
  } else {
	  return document.documentElement.clientHeight;
  }
}

// ä

function iframePost(url, vars, callbackFunction) {
	var mapped = [];
	for(var name in vars){
		mapped.push(encodeURIComponent(name)+"="+encodeURIComponent(vars[name]));
	}
	var postdata = mapped.join("&");
	var postIFrame = document.getElementById("postiframe");
	if (postIFrame == null) {
		var d = document.createElement('DIV');
        d.innerHTML = "<iframe style=\"display:none\" src=\"about:blank\"  id=\"postiframe\" name=\"postiframe\" onload=\"iframePostCallback(this);\"></iframe>";
		d.style.display = "none";
        document.body.appendChild(d);
		postIFrame = document.getElementById("postiframe");
	}
	postIFrame.postcallback = callbackFunction;
	var postIFrameForm = document.getElementById("postiframeform");
	if (postIFrameForm == null) {
		postIFrameForm = document.createElement('form');
		postIFrameForm.name = postIFrameForm.id = "postiframeform";
		postIFrameForm.method = "POST";
		postIFrameForm.target = "postiframe";
		postIFrameForm.style.display = "none";
		var myinput = document.createElement('input');
		var attribute = document.createAttribute("type");
		attribute.nodeValue = "hidden";		
		myinput.setAttributeNode(attribute);
		attribute = document.createAttribute("name");
		attribute.nodeValue = "postdata";		
		myinput.setAttributeNode(attribute);
		myinput.id = "postdata";
		postIFrameForm.appendChild(myinput);
		postIFrameForm = document.body.appendChild(postIFrameForm);
	}
	postIFrameForm.action = url;
	postIFrameForm.postdata.value = postdata;
	postIFrameForm.submit();
}
	
function iframePostCallback(me) {
	me.postcallback();
}

function ajaxPost(url, vars, callbackFunction, error, win){
	var mapped = [];
	for(var name in vars){
	    mapped.push(encodeURIComponent(name)+"="+encodeURIComponent(vars[name]));
	}
	var uri = mapped.join("&");

	if (win == undefined) {
		win = window;
	}
	var request = new win.XMLHttpRequest;
	request.open("POST", url, true);
	request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
//	request.setRequestHeader("Accept-Encoding", "gzip,deflate"); 
	request.setRequestHeader("Content-Length", uri.length);
	request.onreadystatechange = function(){
		if (request.readyState == 4) {
			if (request.status == 200) {
				if (request.responseText){
					callbackFunction(request.responseText);
				}
			}
			else {
				if (error && request.status != 0) {
					error();
				}
			}
		}
	};
	request.send(uri);
	return request;
}

var JSON_escapeable = /["\\\x00-\x1f\x7f-\x9f]/g;
var JSON_meta = {
		'\b': '\\b',
		'\t': '\\t',
		'\n': '\\n',
		'\f': '\\f',
		'\r': '\\r',
		'"' : '\\"',
		'\\': '\\\\'
	};


function JSON_quote(string) {
	return JSON_escapeable.test(string) ?
		'"' + string.replace(JSON_escapeable, function (a) {
			var c = JSON_meta[a];
			if (typeof c === 'string') {
				return c;
			}
			c = a.charCodeAt();
			return '\\u00' + Math.floor(c / 16).toString(16) +
									   (c % 16).toString(16);
		}) + '"' :
		'"' + string + '"';
}


// Copyright 2007 Sergey Ilinsky (http://www.ilinsky.com)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

function setupXMLHTTPRequest(win) {

	// Save reference to earlier defined object implementation (if any)
	var oXMLHttpRequest	= win.XMLHttpRequest;

	// Define on browser type
	var bGecko	= !!window.controllers,
		bIE		= window.document.all && !window.navigator.userAgent.match(/opera/i);

	// Constructor
	function cXMLHttpRequest() {
		this._object	= oXMLHttpRequest ? new oXMLHttpRequest : new win.ActiveXObject("Microsoft.XMLHTTP");
	};

	// BUGFIX: Firefox with Firebug installed would break pages if not executed
	if (bGecko && oXMLHttpRequest.wrapped)
		cXMLHttpRequest.wrapped	= oXMLHttpRequest.wrapped;

	// Public Properties
	cXMLHttpRequest.prototype.readyState	= 0;
	cXMLHttpRequest.prototype.responseText	= "";
	cXMLHttpRequest.prototype.status		= 0;
	
	// Public Methods
	cXMLHttpRequest.prototype.open	= function(sMethod, sUrl, bAsync, sUser, sPassword) {
		// Set the onreadystatechange handler
		var oRequest	= this;

		// BUGFIX: IE - memory leak on page unload
		if (bIE) {
			var fOnUnload	= function() {
//				if (oRequest._object.readyState != 4) {
					fCleanTransport(oRequest);
					oRequest.abort();
//				}
			};
			win.attachEvent("onunload", fOnUnload);
		}

		this._object.onreadystatechange	= function() {
			try {	oRequest.responseText	= oRequest._object.responseText;	} catch (e) {}
			try {	oRequest.readyState			= oRequest._object.readyState;			} catch (e) {}
			try {	oRequest.status			= oRequest._object.status;			} catch (e) {}
			
			if (oRequest.readyState == 4) {
				//
				fCleanTransport(oRequest);

				// BUGFIX: IE - memory leak in interrupted
				if (bIE)
					win.detachEvent("onunload", fOnUnload);
			}

			if (oRequest.onreadystatechange)
				oRequest.onreadystatechange.apply(oRequest);
		};

		this._object.open(sMethod, sUrl, bAsync, sUser, sPassword);

	};
	cXMLHttpRequest.prototype.send	= function(vData) {
		this._object.send(vData);
	};
	cXMLHttpRequest.prototype.abort	= function() {
		this._object.abort();

		// BUGFIX: IE - memory leak
		fCleanTransport(this);
	};
	cXMLHttpRequest.prototype.getAllResponseHeaders	= function() {
		return this._object.getAllResponseHeaders();
	};
	cXMLHttpRequest.prototype.getResponseHeader	= function(sName) {
		return this._object.getResponseHeader(sName);
	};
	cXMLHttpRequest.prototype.setRequestHeader	= function(sName, sValue) {
		return this._object.setRequestHeader(sName, sValue);
	};
	cXMLHttpRequest.prototype.toString	= function() {
		return '[' + "object" + ' ' + "XMLHttpRequest" + ']';
	};
	cXMLHttpRequest.toString	= function() {
		return '[' + "XMLHttpRequest" + ']';
	};

	function fCleanTransport(oRequest) {
		// BUGFIX: IE - memory leak
		oRequest._object.onreadystatechange	= new win.Function;
	};

	// Register new object with window
	win.XMLHttpRequest	= cXMLHttpRequest;
}

setupXMLHTTPRequest(window);

var ua = navigator.userAgent.toLowerCase();
var browserMatch = /(webkit)[ \/]([\w.]+)/.exec( ua ) ||
	/(opera)(?:.*version)?[ \/]([\w.]+)/.exec( ua ) ||
	/(msie) ([\w.]+)/.exec( ua ) ||
	!/compatible/.test( ua ) && /(mozilla)(?:.*? rv:([\w.]+))?/.exec( ua ) ||
	[];
var browser = {version: browserMatch[2] || "0"};
browser[ browserMatch[1] || "" ] = true;

// Comet
var channels;
var lastPollRequest;

var COP_REFRESH_NEW_MAIL = 100;
var COP_PENDING_PICTURE_LIST_ADD = 200;
var COP_PENDING_PICTURE_LIST_REMOVE = 201;
var COP_PENDING_PICTURE_LIST_SIZE = 202;
var COP_WIDGET_DATA = 300;
var COP_WIDGET_JS = 301;
var COP_WIDGET_SHOW = 302;
var COP_WIDGET_UPDATE_STATUS = 303;
var COP_BACKLOG_COMPLETE = 302;
var COP_PENDING_FAKECHECK_LIST_SIZE = 702;
var COP_REFRESH_REPORTED_USERS_COUNT = 800;
var COP_REFRESH_USERS_OF_DAY_VISITS = 1201;
var COP_REMOVE_WIDGET = 1502;

function ChannelOp(channel_name, op_type, parameters) {
	this.channel_name = channel_name; // string
	this.op_type = op_type;                
	this.parameters = parameters; // array of strings
}

function Channel( name ) 
{
	this.name = name;
	this.known_timestamp = 0;
	this.widgetData = {};
}

Channel.prototype.processServerVersion = function( new_op ) {
	this.known_timestamp = new_op.timestamp;		
		
	try {
		switch ( new_op.op_type )
		{					
			case COP_REFRESH_NEW_MAIL:
			{
				this.refreshNewMail(new_op);
				break;
			}
			case COP_PENDING_PICTURE_LIST_ADD:
			{
				this.addPendingPicture(new_op);
				break;
			}
			case COP_PENDING_PICTURE_LIST_REMOVE:
			{
				this.removePendingPicture(new_op);
				break;
			}
			case COP_PENDING_PICTURE_LIST_SIZE:
			{
				if (document.getElementById("adminPendingPictureSetSizeSpan")) {
					document.getElementById("adminPendingPictureSetSizeSpan").innerHTML = "(" + new_op.parameters[0] + ")";
				}
				break;
			}
			case COP_PENDING_FAKECHECK_LIST_SIZE:
			{
				if (document.getElementById("adminPendingFakecheckSetSizeSpan")) {
					document.getElementById("adminPendingFakecheckSetSizeSpan").innerHTML = "(" + new_op.parameters[0] + ")";
				}
				break;
			}
			case COP_REFRESH_REPORTED_USERS_COUNT:
			{
				if (document.getElementById("adminReportSetSizeSpan")) {
					document.getElementById("adminReportSetSizeSpan").innerHTML = "(" + new_op.parameters[0] + ")";
				}
				break;
			}
			case COP_WIDGET_DATA:
			{
				this.widgetData[new_op.parameters[0]] = new_op.parameters[1];
				break;
			}
			case COP_WIDGET_JS:
			{
				eval(new_op.parameters[0]);
				break;
			}
			case COP_WIDGET_SHOW:
			{
				if (this.show) {
					this.show(new_op);
				}
				break;
			}
			case COP_WIDGET_UPDATE_STATUS:
			{
				this.updateStatus(new_op);
				break;
			}
			case COP_BACKLOG_COMPLETE:
			{
				if (this.backlogComplete) {
					this.backlogComplete();
				}
				break;
			}
			case COP_REFRESH_USERS_OF_DAY_VISITS:
			{
				this.updateVisits(new_op);
				break;
			}
			case COP_REMOVE_WIDGET:
			{
				var chan = channels[new_op.parameters[0]];
				if (chan) {
					if (chan.onRemove) {
						chan.onRemove();
					}
				}
				delete channels[new_op.parameters[0]];
				break;
			}
			default:
			{
				this.defaultAction(new_op);
				break;
			}
			break;
		}				
	}
	catch (e) {
		ajaxPost("/action/reportError", {
				widgetId: this.name,
				string: e.toString(),
				windowLocation: window.location.href,
				appLocation: locationWrapper.get()
			},
			function(data){
			});	
	}
};	

Channel.prototype.post = function( op_type, parameters ) {
	postChannelOps([new ChannelOp(this.name, op_type, parameters)]);
};	


// Server RPCs
function pollChannels()
{
	var pollList = "[";
	var first = true;
	for ( var i in channels )	
	{
		var channel = channels[i];
		if ( channel != undefined )
			if (!first)
				pollList = pollList + ",";
			pollList = pollList + "[" + JSON_quote(channel.name) + "," + channel.known_timestamp + "]";
			first = false;
	}	
	pollList = pollList + "]";

	if (lastPollRequest) {
		lastPollRequest.onreadystatechange = new window.Function;
		lastPollRequest.abort();
	}
	
	lastPollRequest = ajaxPost("/action/cometPollChannels", {
			pageId: pageId,
			polllist: pollList
		},
		function(data){
			if (data == "GOTOLOGIN") {
				window.location.href = "/";
				return;
			}
			var data = data.replace( /\r\n/g, "\n" );
			var splitData = data.split("\n");
	
			if (splitData[0] == "ok") {
				var out_versions = eval(splitData[1]);
				pollChannelsCallback(out_versions);
			}
			else {
				alert(splitData[0]);
			}
		},
		function(){
			pollChannelsCallback();
		}, cometWindow);
}

function pollChannelsCallback( ops)
{
	if ( ops != undefined && ops.length != undefined )
	{				
		for (var i = 0; i<ops.length; i++ )		
		{
			var op = ops[i];
			var channel_name = op.channel_name;
			var channel = channels[channel_name];
			if ( channel == null && op.timestamp == 1) {
				channel = new Channel(channel_name);
				channels[channel_name] = channel;
			}
			if ( channel ) {
				channel.processServerVersion( op );
			}
			else {
				// this is expected behavior when switching channels, since polling is asynchronous
				// alert( "pollChannelsCallback got an out_version for unknown channel " + out_version.channel_name );
			}
		}
		if (document.getElementById("header_status") && document.getElementById("header_status").style.display == "block") {
			document.getElementById("header_status").style.display = "none";
		}
		if (document.getElementById("header_stats") && document.getElementById("header_stats").style.display == "") {
			var count = 0;
			for ( var i in channels )	
			{
				count++;
			}
			document.getElementById("header_stats").innerHTML = "[" + count + " channels]";
		}
		window.setTimeout(pollChannels,0);
	}
	else {
		if (document.getElementById("header_status")) {
			document.getElementById("header_status").style.display = "block";
		}
		window.setTimeout(pollChannels, 1000);
	}
}

function postChannelOps(channel_ops)
{
	var opList = "[";
	var first = true;
	for ( var i in channel_ops )	
	{
		var channel_op = channel_ops[i];
		if ( channel_op != undefined) {
			if (!first)
				opList = opList + ",";
			opList = opList + '{"op_type":' + channel_op.op_type + ",";
			opList = opList + '"channel_name":' + JSON_quote(channel_op.channel_name) + ",";
			var parameters = channel_op.parameters;
			var wss_parameters = [];
			if ( parameters != undefined ) 
			{
				if ( typeof parameters == "string" )
					wss_parameters = [parameters];
				else
					wss_parameters = parameters;
			}
			var parameterList = "[";
			var first = true;
			for ( var i in parameters )	
			{
				var parameter = parameters[i];
				if ( parameter != undefined)
					if (!first)
						parameterList = parameterList + ",";
					parameterList = parameterList + JSON_quote(parameter);
					first = false;
			}	
			parameterList = parameterList + "]";
			opList = opList + '"parameters":' + parameterList + "}";
			first = false;
		}
	}	
	opList = opList + "]";

	ajaxPost("/action/cometPostChannelOps", {
			oplist: opList
		},
		function(data){
			if (data == "GOTOLOGIN") {
				window.location.href = "/";
				return;
			}
			var data = data.replace( /\r\n/g, "\n" );
			var splitData = data.split("\n");
	
			if (splitData[0] != "ok") {
				alert(splitData[0]);
			}
		},
		function(){
			//alert("ERROR");
		}, cometWindow);				
}

var cometWindow;
var pageId;

function setupComet(comethostid, setPageId) {
	pageId = setPageId;
	var d = document.createElement('DIV');
	d.innerHTML = "<iframe style=\"display:none\" src=\"http://chat" + comethostid + ".wie-ich.de/cometiframe.jsp\"  id=\"cometIFrame\" name=\"cometIFrame\" onload=\"startComet();\"></iframe>";
	d.style.display = "none";
	document.body.appendChild(d);
}

function startComet() {
	cometWindow = window.frames["cometIFrame"];
	setupXMLHTTPRequest(cometWindow);
	channels = new Object();
	if (locationWrapper.get().indexOf("!") == 0) { // TODO always do this
		postChannelOps([new ChannelOp(pageId + "_0", 1500,  [locationWrapper.get()])]);
	}
	
	// Start polling. polling is a blocking wait and will iteratively call itself			
	window.setTimeout(pollChannels,0);
}

var locationWrapper = {
	put: function(hash, win) {
		(win || window).location.hash = encodeURIComponent(hash);
	},
	get: function(win) {
		var hash = ((win || window).location.hash).replace(/^#/, '');
		return browser.mozilla ? hash : decodeURIComponent(hash);
	}
};

var iframeWrapper = {
	id: "__jQuery_history",
	_document: function() {
		return document.getElementById(this.id).contentWindow.document;
	},
	put: function(hash) {
		var doc = this._document();
		doc.open();
		doc.write("<script type=\"text/javascript\">document.domain = \"wie-ich.de\"</script>");
		doc.close();
		locationWrapper.put(hash, doc);
	},
	get: function() {
		return locationWrapper.get(this._document());
	}
};

var ajaxHistory = {
	appState: undefined,
	callback: undefined
};

if(browser.msie && (browser.version < 8 || document.documentMode < 8)) {
	var d = document.createElement('DIV');
	d.innerHTML = "<iframe id=\"__jQuery_history\" style=\"display:none\" src=\"javascript:false;\"></iframe>";
	d.style.display = "none";
	document.body.appendChild(d);
	var doc = iframeWrapper._document();
	doc.open();
	doc.write("<script type=\"text/javascript\">document.domain = \"wie-ich.de\"</script>");
	doc.close();
	ajaxHistory.init = function(callback) {
		ajaxHistory.callback = callback;
		var current_hash = locationWrapper.get();
		ajaxHistory.appState = current_hash;
		iframeWrapper.put(current_hash);
		ajaxHistory.callback(current_hash);
		setInterval(ajaxHistory.check, 30);
	},
	ajaxHistory.check = function() {
		var current_hash = iframeWrapper.get();
		if(current_hash != ajaxHistory.appState) {
			locationWrapper.put(current_hash);
			ajaxHistory.appState = current_hash;
			ajaxHistory.callback(current_hash);
		}
	},
	ajaxHistory.load = function(hash) {
		if(hash != ajaxHistory.appState) {
			locationWrapper.put(hash);
			iframeWrapper.put(hash);
			ajaxHistory.appState = hash;
			ajaxHistory.callback(hash);
		}
	}
} else {
	ajaxHistory.init = function(callback) {
		ajaxHistory.callback = callback;
		var current_hash = locationWrapper.get();
		ajaxHistory.appState = current_hash;
		ajaxHistory.callback(current_hash);
		setInterval(ajaxHistory.check, 30);
	};
	ajaxHistory.check = function() {
		var current_hash = locationWrapper.get();
		if(current_hash != ajaxHistory.appState) {
			ajaxHistory.appState = current_hash;
			ajaxHistory.callback(current_hash);
		}
	};
	ajaxHistory.load = function(hash) {
		if(hash != ajaxHistory.appState) {
			locationWrapper.put(hash);
			ajaxHistory.appState = hash;
			ajaxHistory.callback(hash);
		}
	};
}

document.domain = "wie-ich.de"; // only after initialisation of history iframe

function gotopage(page) {
	moreouttimertimeout();
	ajaxHistory.load(page);
}

ajaxHistory.init(function(url) {
	if (channels) {
		if (url == "!feedback") {
//			alert("goto feedback");
			postChannelOps([new ChannelOp(pageId + "_0", 1500,  [url])]);
		}
		else if (url == "") {
//			alert("goto main");
			postChannelOps([new ChannelOp(pageId + "_0", 1500,  [url])]);
		}
		else {
			alert("Seite " + url + " nicht gefunden.");
		}
	}
});

