// ä

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 = makeURL("www", "");
				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.ignored) {
							jsonUser.ignored = true;
						}
						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 && window.main_channel && jsonAuthUser.userId != jsonUser.userId) {
			if (jsonUser.ignored) {
				outString = outString + "<div><a href=\"javascript:unignore(" + jsonUser.userId + ");\" class=\"linkbin16\">Ign. beenden</a></div>";
			}
			else {
				outString = outString + "<div><a href=\"javascript:ignore(" + jsonUser.userId + ");\" class=\"linkbin16\">Ignorieren</a></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 moreTouchStart(e, owner, id) {
	moreId = id;
	this.onmouseover = null;
	this.onmouseout = null;
	this.onclick = null;
	if (moreShowing) {
		moreouttimertimeout();
	}
	else {
		moreovertimertimeout(true);
	}
}

function moremouseover(e, owner, id) {
	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(nofocus) {
	if (document.getElementById("menumore") && moreId == "club") {
		document.getElementById("menumore").style.display = "none";
	}
	if (moreId == "more") {
		if (document.getElementById("menuclub")) {
			document.getElementById("menuclub").style.display = "none";
		}
		document.getElementById("menumore").className="sim_menu_more lighter";
		document.getElementById("menumore_inner").className="sim_menu_more_i dark";
		document.getElementById("menumore").style.left = "-77px";
		document.getElementById("menumore").style.width = "350px";
		if (findPosX(document.getElementById("menumorebutton")) -18 + 350 > document.documentElement.clientWidth) {
			var left = Math.max(10, document.documentElement.clientWidth - 350) - findPosX(document.getElementById("menumorebutton"));
			document.getElementById("menumore").style.left = left + "px";
			document.getElementById("menumore").style.width = Math.min(document.documentElement.clientWidth, 350) + "px";
		}
	}
	var menumore = document.getElementById("menu" + moreId);
	menumore.style.display = "block";
	if (!nofocus && !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=" + location.hostname.replace(/.*\.([^\.]*\.[^\.]*)$/, "$1");
			newwindow.location.href= makeURL("chat" + Math.floor(Math.random()*99999000 + 100), "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, cancel){
	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"); 
	if (browser.msie) {
		request.setRequestHeader("Content-Length", uri.length);
	}
	request.onreadystatechange = function(){
		if (request.readyState == 4) {
			busy = false;
			if (request.status == 200) {
				if (request.responseText){
					callbackFunction(request.responseText);
				}
			}
			else if (request.status == 0 && cancel) {
				cancel();
			}
			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;


function Dictionary() {
	this.keys = [];
}

Dictionary.prototype.add = function(k, v) {
	this[k] = v;
	this.keys.push(k);
};

Dictionary.prototype.remove = function(k) {
	delete this[k];
	for (var i=0; i<this.keys.length; i++) {
		if (this.keys[i] == k) {
			this.keys.splice(i, 1);
		}
	}
};

// Comet
var channels;
var lastPollRequest;

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_NEW_MAIL_COUNT = 1100;
var COP_REFRESH_USERS_OF_DAY_VISITS = 1201;
var COP_REMOVE_WIDGET = 1502;
var COP_LAYOUT = 1900;

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 = {};
	this.__pendingRequests = 0;
	this.__opQueue = [];
	this.__started = false;
}

Channel.prototype.runOrEnqueue = function( op ) {
	if (this.__started && this.__pendingRequests <= 0) {
		try {
			op();
		}
		catch (e) {
			ajaxPost("/action/reportError", {
					widgetId: this.name,
					string: e.toString() + (busy?" (busy)":" (not busy)"),
					windowLocation: window.location.href,
					appLocation: locationWrapper.get()
				},
				function(data){
				});	
			busy = false;
			jsonBusy = false;
		}
	}
	else {
		this.__opQueue.push(op);
	}
};

Channel.prototype.incrementPendingRequests = function() {
	this.__pendingRequests++;
};

Channel.prototype.decrementPendingRequests = function() {
	this.__pendingRequests--;
	this.__start();
};

Channel.prototype.__start = function() {
	if (this.__pendingRequests <= 0) {
		var passed = false;
		for (var i=0; i<channels.keys.length; i++) {
			var channel = channels[channels.keys[i]];
			if ( channel != undefined ) {
				if (channel == this) {
					passed = true;
					while (this.__opQueue.length > 0) {
						try {
							(this.__opQueue.shift())();
						}
						catch (e) {
							ajaxPost("/action/reportError", {
									widgetId: this.name,
									string: e.toString() + (busy?" (busy)":" (not busy)"),
									windowLocation: window.location.href,
									appLocation: locationWrapper.get()
								},
								function(data){
								});	
							busy = false;
							jsonBusy = false;
						}
					}
					this.__started = true;
				}
				else {
					if (!passed) {
						if (channel.__pendingRequests > 0) {
							// need to wait for this one
							break;
						}
					}
					else {
						// this one comes later, so start it as well if it is ready
						if (channel.__pendingRequests <= 0) {
							while (channel.__opQueue.length > 0) {
								try {
									(channel.__opQueue.shift())();
								}
								catch (e) {
									ajaxPost("/action/reportError", {
											widgetId: channel.name,
											string: e.toString() + (busy?" (busy)":" (not busy)"),
											windowLocation: window.location.href,
											appLocation: locationWrapper.get()
										},
										function(data){
										});	
									busy = false;
									jsonBusy = false;
								}
							}
							channel.__started = true;
						}
					}
				}
			}
		}
	}
};

Channel.prototype.processServerVersion = function( new_op ) {
	this.known_timestamp = new_op.timestamp;		
		
	try {
		switch ( new_op.op_type )
		{					
			case COP_REFRESH_NEW_MAIL_COUNT:
			{
				var self = this;
				this.runOrEnqueue(function() {
							self.refreshNewMail(new_op);
					   });
				break;
			}
			case COP_PENDING_PICTURE_LIST_ADD:
			{
				var self = this;
				this.runOrEnqueue(function() {
							self.addPendingPicture(new_op);
					   });
				break;
			}
			case COP_PENDING_PICTURE_LIST_REMOVE:
			{
				var self = this;
				this.runOrEnqueue(function() {
							self.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:
			{
				if (new_op.parameters.length >= 2 && typeof window.localStorage != 'undefined') {
					try {
						localStorage.setItem("file_" + new_op.parameters[2], new_op.parameters[1]);
						localStorage.setItem("file_" + new_op.parameters[2] + "_md5", hex_md5(new_op.parameters[1]));
					}
					catch (ex) {}
				}
				this.test = new_op.parameters[1];
				this.widgetData[new_op.parameters[0]] = new_op.parameters[1];
				this.decrementPendingRequests();
				break;
			}
			case COP_WIDGET_JS:
			{
				if (new_op.parameters.length >= 1 && typeof window.localStorage != 'undefined') {
					try {
						localStorage.setItem("file_" + new_op.parameters[1], new_op.parameters[0]);
						localStorage.setItem("file_" + new_op.parameters[1] + "_md5", hex_md5(new_op.parameters[0]));
					}
					catch (ex) {}
				}
				this.test = new_op.parameters[0];
				eval(new_op.parameters[0]);
				this.decrementPendingRequests();
				break;
			}
			case 307: // COP_WIDGET_DATA_CACHED
			{
				if (typeof window.localStorage != 'undefined' && new_op.parameters[2] == localStorage.getItem("file_" + new_op.parameters[1] + "_md5")) {
					this.widgetData[new_op.parameters[0]] = localStorage.getItem("file_" + new_op.parameters[1]);
				}
				else {
					this.post( 308, [new_op.parameters[0], new_op.parameters[1]] ); // COP_REQUEST_DATA
					this.incrementPendingRequests();
				}
				break;
			}
			case 305: // COP_WIDGET_JS_CACHED
			{
				if (typeof window.localStorage != 'undefined' && new_op.parameters[1] == localStorage.getItem("file_" + new_op.parameters[0] + "_md5")) {
					eval(localStorage.getItem("file_" + new_op.parameters[0]));
					this.__start();
				}
				else {
					this.post( 306, [new_op.parameters[0]] ); // COP_REQUEST_JS
					this.incrementPendingRequests();
				}
				break;
			}
			case COP_WIDGET_SHOW:
			{
				var self = this;
				this.runOrEnqueue(function() {
							if (self.show) {
								self.show(new_op);
							}
					   });
				break;
			}
			case COP_WIDGET_UPDATE_STATUS:
			{
				var self = this;
				this.runOrEnqueue(function() {
							self.updateStatus(new_op);
					   });
				break;
			}
			case COP_BACKLOG_COMPLETE:
			{
				var self = this;
				this.runOrEnqueue(function() {
							if (self.backlogComplete) {
								self.backlogComplete();
							}
					   });
				break;
			}
			case COP_REFRESH_USERS_OF_DAY_VISITS:
			{
				var self = this;
				this.runOrEnqueue(function() {
							self.updateVisits(new_op);
					   });
				break;
			}
			case COP_REMOVE_WIDGET:
			{
				var chan = channels[new_op.parameters[0]];
				if (chan) {
					if (chan.onRemove) {
						chan.onRemove();
					}
				}
				channels.remove(new_op.parameters[0]);
				break;
			}
			case COP_LAYOUT:
			{
				setLayout(new_op);
				break;
			}
			default:
			{
				var self = this;
				this.runOrEnqueue(function() {
							self.defaultAction(new_op);
					   });
				break;
			}
			break;
		}				
	}
	catch (e) {
		ajaxPost("/action/reportError", {
				widgetId: this.name,
				string: e.toString() + (busy?" (busy)":" (not busy)"),
				windowLocation: window.location.href,
				appLocation: locationWrapper.get()
			},
			function(data){
			});	
		busy = false;
		jsonBusy = false;
	}
};	

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=0; i<channels.keys.length; i++) {
		var channel = channels[channels.keys[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 = makeURL("www", "");
				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(null, true);
		});
}

function pollChannelsCallback(ops, cancel)
{
	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.add(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 = channels.keys.length + "/" + count + " channels]";
		}
		window.setTimeout(pollChannels,0);
	}
	else if (cancel) {
		window.setTimeout(pollChannels, 10);
	}
	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 = makeURL("www", "");
				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) {
	if (window.location.hash != "") window.location.hash = window.location.hash; // defeat IE bug
	pageId = setPageId;
	var d = document.createElement('DIV');
	d.innerHTML = "<iframe style=\"display:none\" src=\"" + makeURL("chat" + comethostid, "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 Dictionary();
	if (locationWrapper.get().indexOf("!") == 0) { // TODO always do this
		if (document.getElementById("middlec")) {
			document.getElementById("middlec").innerHTML = "<br /><br /><br />wird geladen...";
		}
		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 = \"" + location.hostname.replace(/.*\.([^\.]*\.[^\.]*)$/, "$1") + "\"</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 = \"" + location.hostname.replace(/.*\.([^\.]*\.[^\.]*)$/, "$1") + "\"</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 = location.hostname.replace(/.*\.([^\.]*\.[^\.]*)$/, "$1"); // only after initialisation of history iframe

function gotopage(element, page, e) {
	if (element && e && (e.altKey || e.ctrlKey || e.shiftKey 
						 || browser.msie && browser.version < 9 && (element.b == 4 || e.button == 4 || element.b == 2 || e.button == 2) 
						 || (!browser.msie || browser.version >= 9) && (element.b ==1 || e.button ==1 || element.b ==2 || e.button ==2))) {
		return true;
	}
	else {
		moreouttimertimeout();
		ajaxHistory.load(page);
		return false;
	}
}

ajaxHistory.init(function(url) {
	if (channels) {
		if (url == "!messages") {
			if (document.getElementById("messagespagehead")) {
				document.getElementById("messagespagehead").style.display = "";
				document.getElementById("messagespagecontent").style.display = "";
				if (document.getElementById("messagereadhead")) {
					document.getElementById("messagereadhead").parentNode.removeChild(document.getElementById("messagereadhead"));
					document.getElementById("messagereadcontent").parentNode.removeChild(document.getElementById("messagereadcontent"));
				}
				if (document.getElementById("messagewritehead")) {
					document.getElementById("messagespagehead").widget.destroyWrite();
					document.getElementById("messagewritehead").parentNode.removeChild(document.getElementById("messagewritehead"));
					document.getElementById("messagewritecontent").parentNode.removeChild(document.getElementById("messagewritecontent"));
				}
				if ("oldX" in document.getElementById("messagespagehead")) {
					window.scrollTo(document.getElementById("messagespagehead").oldX, document.getElementById("messagespagehead").oldY);
				}
			}
			else {
				postChannelOps([new ChannelOp(pageId + "_0", 1500,  [url])]);
			}
			refreshAd();
		}
		else if (url.indexOf("!read") == 0) {
			if (document.getElementById("messagewritehead")) {
				document.getElementById("messagespagehead").widget.destroyWrite();
				document.getElementById("messagewritehead").parentNode.removeChild(document.getElementById("messagewritehead"));
				document.getElementById("messagewritecontent").parentNode.removeChild(document.getElementById("messagewritecontent"));
			}
			postChannelOps([new ChannelOp(pageId + "_0", 1500,  [url])]);
			refreshAd();
		}
		else if (url.indexOf("!write") == 0) {
			postChannelOps([new ChannelOp(pageId + "_0", 1500,  [url])]);
		}
		else if (url.indexOf("!Foto_Battle_challenge") == 0 && document.getElementById("challengepagehead")) {
			document.getElementById("challengepagehead").widget.showLevelCallback(url);
			refreshAd(true);
		}
		else if (url == "!") { // TODO change to ""
			postChannelOps([new ChannelOp(pageId + "_0", 1500,  [url])]);
			refreshAd(true);
		}
		else if (url == "") {
			if (window.location.pathname == "/") {
				postChannelOps([new ChannelOp(pageId + "_0", 1500,  [url])]);
				refreshAd(true);
			}
			else {
				window.location.href = window.location.href; // TODO remove
			}
		}
		else {
			postChannelOps([new ChannelOp(pageId + "_0", 1500,  [url])]);
			refreshAd();
		}
	}
});

function reloadPage() {
	postChannelOps([new ChannelOp(pageId + "_0", 1500,  [locationWrapper.get()])]);
	refreshAd();
}

function refreshAd(clear) {
	try {
		if (!window.fb && window.location.protocol != "https:") {
			if (document.getElementById("sim_adbanner_sky")) {
				if (clear) {
					document.getElementById("sim_adbanner_sky").innerHTML = "";
				}
				else {
					if (document.documentElement.clientWidth >= 785) {
						var html = "<iframe id=\"adiframesky\" style=\"visibility:hidden\" onload=\"this.style.visibility='visible';\" " + 
								"src=\"http://ads.adrush.de/ad?c=1000700&t=2641588";
						if (window.adrush) {
							html = html + "&w=" + window.adrush;
						}
						html = html + "\" width=\"160\" height=\"600\" frameborder=\"0\" scrolling=\"no\"></iframe>";
						document.getElementById("sim_adbanner_sky").innerHTML = html;
					}
				}
			}
			if (document.getElementById("headeraboutold") && document.getElementById("banner")) {
				if (clear) {
					document.getElementById("banner").innerHTML = "";
				}
				else {
					var html = "<iframe id=\"adiframe\" style=\"visibility:hidden\" onload=\"this.style.visibility='visible';\" " + 
							"src=\"http://ads.adrush.de/ad?c=1000700&t=1000901";
					if (window.adrush) {
						html = html + "&w=" + window.adrush;
					}
					html = html + "\" width=\"468\" height=\"60\" frameborder=\"0\" scrolling=\"no\"></iframe>";
					document.getElementById("banner").innerHTML = html;
				}
			}
		}
	}
	catch (e) {
		// do noth
	}
}

function setLayout(new_op) {
	var data; eval("data = " + new_op.parameters[0]);
	changecss(".darkborder", "background-color", "#" + data.colorDark);
	changecss(".darkborder", "border-color", "#" + data.lighter + " #" + data.darker + " #" + data.darker + " #" + data.lighter);
	changecss("div", "SCROLLBAR-FACE-COLOR", "#" + data.colorDark);
	changecss("div", "SCROLLBAR-HIGHLIGHT-COLOR", "#" + data.lighter);
	changecss("div", "SCROLLBAR-SHADOW-COLOR", "#" + data.darker);
	changecss("div", "SCROLLBAR-TRACK-COLOR", "#" + data.lighter2);
	changecss("div", "SCROLLBAR-DARKSHADOW-COLOR", "#" + data.darker2);
	changecss("div", "SCROLLBAR-BASE-COLOR", "#" + data.colorDark);
	changecss("div", "scrollbar-3d-light-color", "#" + data.lighter);
	changecss("textarea", "SCROLLBAR-FACE-COLOR", "#" + data.colorDark);
	changecss("textarea", "SCROLLBAR-HIGHLIGHT-COLOR", "#" + data.lighter);
	changecss("textarea", "SCROLLBAR-SHADOW-COLOR", "#" + data.darker);
	changecss("textarea", "SCROLLBAR-TRACK-COLOR", "#" + data.lighter2);
	changecss("textarea", "SCROLLBAR-DARKSHADOW-COLOR", "#" + data.darker2);
	changecss("textarea", "SCROLLBAR-BASE-COLOR", "#" + data.colorDark);
	changecss("textarea", "scrollbar-3d-light-color", "#" + data.lighter);
	changecss(".light div", "SCROLLBAR-FACE-COLOR", "#" + data.lightDim);
	changecss(".light div", "SCROLLBAR-HIGHLIGHT-COLOR", "#" + data.lightDimLighter);
	changecss(".light div", "SCROLLBAR-SHADOW-COLOR", "#" + data.lightDimDarker);
	changecss(".light div", "SCROLLBAR-TRACK-COLOR", "#" + data.lightDimLighter2);
	changecss(".light div", "SCROLLBAR-DARKSHADOW-COLOR", "#" + data.lightDimDarker2);
	changecss(".light div", "SCROLLBAR-BASE-COLOR", "#" + data.lightDim);
	changecss(".light div", "scrollbar-3d-light-color", "#" + data.lightDimLighter);
	changecss(".light", "background-color", "#" + data.colorLight);
	changecss(".lighter", "background-color", "#" + data.lighter);
	changecss(".dark", "background-color", "#" + data.colorDark);
	changecss(".darker", "background-color", "#" + data.darker);
	changecss(".sim_menu_more", "border-right-color", "#" + data.lighter);
	changecss(".sim_menu_more_i", "border-color", "#" + data.darker);
	changecss(".purbu", "background-color", "#" + data.darkPale);
	changecss(".sim_header", "background-image", "url(/gfx/layout/" + data.pictureIdBackground + ".gif)");
	changecss(".sim_header_club", "background-image", "url(/gfx/layout/" + data.pictureIdBackgroundClub + ".gif)");
}

function changecss(theClass,element,value) {
	//Last Updated on June 23, 2009
	//documentation for this script at
	//http://www.shawnolson.net/a/503/altering-css-class-attributes-with-javascript.html
	var cssRules;
	
	var added = false;
	for (var S = 0; S < document.styleSheets.length; S++){
		try {
			if (document.styleSheets[S]['rules']) {
				cssRules = 'rules';
			} else if (document.styleSheets[S]['cssRules']) {
				cssRules = 'cssRules';
			}
			
			for (var R = 0; R < document.styleSheets[S][cssRules].length; R++) {
				if (document.styleSheets[S][cssRules][R].selectorText == theClass) {
					if(document.styleSheets[S][cssRules][R].style[element]){
						document.styleSheets[S][cssRules][R].style[element] = value;
						added=true;
						break;
					}
				}
			}
			if(!added){
				if(document.styleSheets[S].insertRule){
					document.styleSheets[S].insertRule(theClass+' { '+element+': '+value+'; }',document.styleSheets[S][cssRules].length);
				} else if (document.styleSheets[S].addRule) {
					document.styleSheets[S].addRule(theClass,element+': '+value+';');
				}
			}
		}
		catch (e) { 
			// security error for remote / plugin stylesheets 
		}
	}
}

function wiScrollTo(x, y) {
	scrollTo(0, 0);
	if (typeof(FB) != "undefined") {
		FB.Canvas.setSize({height:750});
		var fburl = window.location.protocol + "//static.ak.facebook.com/xd_receiver_v0.4.php?r=1#%7B%22id%22%3A0%2C%22sc%22%3Anull%2C%22sf%22%3A%22%22%2C%22sr%22%3A2%2C%22h%22%3A%22iframeOuterServer%22%2C%22sid%22%3A%220.957%22%2C%22t%22%3A0%7D%5B0%2C%22iframeInnerClient%22%2C%22scrollTo%22%2C%7B%22x%22%3A" + x + "%2C%22y%22%3A" + y + "%7D%2Cfalse%5D";
		var fbif = '<iframe style="border:none;width:1px;height:1px;position:absolute;top:0px;left:0px;" src="' + fburl + '" onload="if(document.getElementById(\'scrollTop\')){document.getElementById(\'scrollTop\').parentNode.removeChild(document.getElementById(\'scrollTop\'));}"></iframe>';
		var div = document.createElement("div");
		div.id = "scrollTop";
		div.style.visibility = "hidden";
		div.innerHTML = fbif;
		document.body.appendChild(div);
	}
}

function makeURL(host, path) {
	if (host == "www" || window.location.protocol == "https:") {
		host = location.hostname.replace(/(.*)\.[^\.]*\.[^\.]*$/, "$1");
	}
	if (window.location.protocol == "https:") {
		return "https://" + host + "." + location.hostname.replace(/.*\.([^\.]*\.[^\.]*)$/, "$1") + "/" + path;
	}
	else {
		return "http://" + host + "." + location.hostname.replace(/.*\.([^\.]*\.[^\.]*)$/, "$1") + "/" + path;
	}
}

/*
 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
 * Digest Algorithm, as defined in RFC 1321.
 * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for more info.
 */
var hexcase=0;function hex_md5(a){return rstr2hex(rstr_md5(str2rstr_utf8(a)))}function hex_hmac_md5(a,b){return rstr2hex(rstr_hmac_md5(str2rstr_utf8(a),str2rstr_utf8(b)))}function md5_vm_test(){return hex_md5("abc").toLowerCase()=="900150983cd24fb0d6963f7d28e17f72"}function rstr_md5(a){return binl2rstr(binl_md5(rstr2binl(a),a.length*8))}function rstr_hmac_md5(c,f){var e=rstr2binl(c);if(e.length>16){e=binl_md5(e,c.length*8)}var a=Array(16),d=Array(16);for(var b=0;b<16;b++){a[b]=e[b]^909522486;d[b]=e[b]^1549556828}var g=binl_md5(a.concat(rstr2binl(f)),512+f.length*8);return binl2rstr(binl_md5(d.concat(g),512+128))}function rstr2hex(c){try{hexcase}catch(g){hexcase=0}var f=hexcase?"0123456789ABCDEF":"0123456789abcdef";var b="";var a;for(var d=0;d<c.length;d++){a=c.charCodeAt(d);b+=f.charAt((a>>>4)&15)+f.charAt(a&15)}return b}function str2rstr_utf8(c){var b="";var d=-1;var a,e;while(++d<c.length){a=c.charCodeAt(d);e=d+1<c.length?c.charCodeAt(d+1):0;if(55296<=a&&a<=56319&&56320<=e&&e<=57343){a=65536+((a&1023)<<10)+(e&1023);d++}if(a<=127){b+=String.fromCharCode(a)}else{if(a<=2047){b+=String.fromCharCode(192|((a>>>6)&31),128|(a&63))}else{if(a<=65535){b+=String.fromCharCode(224|((a>>>12)&15),128|((a>>>6)&63),128|(a&63))}else{if(a<=2097151){b+=String.fromCharCode(240|((a>>>18)&7),128|((a>>>12)&63),128|((a>>>6)&63),128|(a&63))}}}}}return b}function rstr2binl(b){var a=Array(b.length>>2);for(var c=0;c<a.length;c++){a[c]=0}for(var c=0;c<b.length*8;c+=8){a[c>>5]|=(b.charCodeAt(c/8)&255)<<(c%32)}return a}function binl2rstr(b){var a="";for(var c=0;c<b.length*32;c+=8){a+=String.fromCharCode((b[c>>5]>>>(c%32))&255)}return a}function binl_md5(p,k){p[k>>5]|=128<<((k)%32);p[(((k+64)>>>9)<<4)+14]=k;var o=1732584193;var n=-271733879;var m=-1732584194;var l=271733878;for(var g=0;g<p.length;g+=16){var j=o;var h=n;var f=m;var e=l;o=md5_ff(o,n,m,l,p[g+0],7,-680876936);l=md5_ff(l,o,n,m,p[g+1],12,-389564586);m=md5_ff(m,l,o,n,p[g+2],17,606105819);n=md5_ff(n,m,l,o,p[g+3],22,-1044525330);o=md5_ff(o,n,m,l,p[g+4],7,-176418897);l=md5_ff(l,o,n,m,p[g+5],12,1200080426);m=md5_ff(m,l,o,n,p[g+6],17,-1473231341);n=md5_ff(n,m,l,o,p[g+7],22,-45705983);o=md5_ff(o,n,m,l,p[g+8],7,1770035416);l=md5_ff(l,o,n,m,p[g+9],12,-1958414417);m=md5_ff(m,l,o,n,p[g+10],17,-42063);n=md5_ff(n,m,l,o,p[g+11],22,-1990404162);o=md5_ff(o,n,m,l,p[g+12],7,1804603682);l=md5_ff(l,o,n,m,p[g+13],12,-40341101);m=md5_ff(m,l,o,n,p[g+14],17,-1502002290);n=md5_ff(n,m,l,o,p[g+15],22,1236535329);o=md5_gg(o,n,m,l,p[g+1],5,-165796510);l=md5_gg(l,o,n,m,p[g+6],9,-1069501632);m=md5_gg(m,l,o,n,p[g+11],14,643717713);n=md5_gg(n,m,l,o,p[g+0],20,-373897302);o=md5_gg(o,n,m,l,p[g+5],5,-701558691);l=md5_gg(l,o,n,m,p[g+10],9,38016083);m=md5_gg(m,l,o,n,p[g+15],14,-660478335);n=md5_gg(n,m,l,o,p[g+4],20,-405537848);o=md5_gg(o,n,m,l,p[g+9],5,568446438);l=md5_gg(l,o,n,m,p[g+14],9,-1019803690);m=md5_gg(m,l,o,n,p[g+3],14,-187363961);n=md5_gg(n,m,l,o,p[g+8],20,1163531501);o=md5_gg(o,n,m,l,p[g+13],5,-1444681467);l=md5_gg(l,o,n,m,p[g+2],9,-51403784);m=md5_gg(m,l,o,n,p[g+7],14,1735328473);n=md5_gg(n,m,l,o,p[g+12],20,-1926607734);o=md5_hh(o,n,m,l,p[g+5],4,-378558);l=md5_hh(l,o,n,m,p[g+8],11,-2022574463);m=md5_hh(m,l,o,n,p[g+11],16,1839030562);n=md5_hh(n,m,l,o,p[g+14],23,-35309556);o=md5_hh(o,n,m,l,p[g+1],4,-1530992060);l=md5_hh(l,o,n,m,p[g+4],11,1272893353);m=md5_hh(m,l,o,n,p[g+7],16,-155497632);n=md5_hh(n,m,l,o,p[g+10],23,-1094730640);o=md5_hh(o,n,m,l,p[g+13],4,681279174);l=md5_hh(l,o,n,m,p[g+0],11,-358537222);m=md5_hh(m,l,o,n,p[g+3],16,-722521979);n=md5_hh(n,m,l,o,p[g+6],23,76029189);o=md5_hh(o,n,m,l,p[g+9],4,-640364487);l=md5_hh(l,o,n,m,p[g+12],11,-421815835);m=md5_hh(m,l,o,n,p[g+15],16,530742520);n=md5_hh(n,m,l,o,p[g+2],23,-995338651);o=md5_ii(o,n,m,l,p[g+0],6,-198630844);l=md5_ii(l,o,n,m,p[g+7],10,1126891415);m=md5_ii(m,l,o,n,p[g+14],15,-1416354905);n=md5_ii(n,m,l,o,p[g+5],21,-57434055);o=md5_ii(o,n,m,l,p[g+12],6,1700485571);l=md5_ii(l,o,n,m,p[g+3],10,-1894986606);m=md5_ii(m,l,o,n,p[g+10],15,-1051523);n=md5_ii(n,m,l,o,p[g+1],21,-2054922799);o=md5_ii(o,n,m,l,p[g+8],6,1873313359);l=md5_ii(l,o,n,m,p[g+15],10,-30611744);m=md5_ii(m,l,o,n,p[g+6],15,-1560198380);n=md5_ii(n,m,l,o,p[g+13],21,1309151649);o=md5_ii(o,n,m,l,p[g+4],6,-145523070);l=md5_ii(l,o,n,m,p[g+11],10,-1120210379);m=md5_ii(m,l,o,n,p[g+2],15,718787259);n=md5_ii(n,m,l,o,p[g+9],21,-343485551);o=safe_add(o,j);n=safe_add(n,h);m=safe_add(m,f);l=safe_add(l,e)}return Array(o,n,m,l)}function md5_cmn(h,e,d,c,g,f){return safe_add(bit_rol(safe_add(safe_add(e,h),safe_add(c,f)),g),d)}function md5_ff(g,f,k,j,e,i,h){return md5_cmn((f&k)|((~f)&j),g,f,e,i,h)}function md5_gg(g,f,k,j,e,i,h){return md5_cmn((f&j)|(k&(~j)),g,f,e,i,h)}function md5_hh(g,f,k,j,e,i,h){return md5_cmn(f^k^j,g,f,e,i,h)}function md5_ii(g,f,k,j,e,i,h){return md5_cmn(k^(f|(~j)),g,f,e,i,h)}function safe_add(a,d){var c=(a&65535)+(d&65535);var b=(a>>16)+(d>>16)+(c>>16);return(b<<16)|(c&65535)}function bit_rol(a,b){return(a<<b)|(a>>>(32-b))};
