/******************************** JS extensions ***************************/
function $(id) {
  	return document.getElementById(id);
}
Array.prototype.contains = function (element) {
    for (var i = 0; i < this.length; i++) {
            if (this[i]==element) {
                return true;
            }
    }        
    return false;
};
/******************************** Initialisation ***************************/
var SECOND=1000;
var MINUTE=60*SECOND;
var HOUR=60*MINUTE;
var DAY=24*HOUR;
var YEAR=365*DAY;

/******************************** Cookies ***************************/

function loadCookieData()
{
	var cookieData = openCookie("PoppenWIO");
	window.logged = (cookieData != null);
	if(window.logged)
	{
		window.paying = cookieData.indexOf("normal") == -1;
		window.rate = cookieData.charAt(cookieData.length-1) == "*";
		window.userPrefs = openCookie("PoppenPref");
		window.userSessn = openCookie("PHPSESSID");
		window.userBBid = openCookie("bbuserid");
	}
	else
	{
		window.paying = false;
		window.userPrefs = undefined;
		window.userSessn = undefined;
		window.userBBid = undefined;
	}
	return cookieData;	
}



function raiseFlag(flagToSet){
	var flag = flagToSet + "Flag";
	var expDate = new Date();
	var expDateMs = expDate.getTime() + (1*YEAR);
	expDate.setTime(expDateMs);
	document.cookie = flag + "=true; expires=" + expDate.toGMTString();
}

function lowerFlag(flagToLower){
	var flag = flagToLower + "Flag";
	consumeCookie(flag);
}

function openCookie(dataToFind){
	var messenger = document.cookie;

	var messengerSize = messenger.length;
	var idx = 0;
	while(idx < messengerSize){
		var scoutIdx = idx + dataToFind.length + 1;
		if(messenger.substring(idx, scoutIdx) == (dataToFind + "=")){
			var endIdx = messenger.indexOf(";", scoutIdx);
			if(endIdx ==  -1){
				endIdx = messengerSize;
			}
			return unescape(messenger.substring(scoutIdx,endIdx));
		}
		idx = messenger.indexOf(" ", idx) + 1;
		if(idx==0)
		{
			break;
		}
	}
	return null;
}

function consumeCookie(dataToFind){
	var date = new Date();
	date.setTime(date.getTime()-1*DAY);
	document.cookie = dataToFind + "=; expires=" +date.toGMTString();
}




/******************************** Utilities ***************************/


function replaceSpecialChars(s) {
	/*Fixes umlauts*/
	s = s.replace("&Auml;", String.fromCharCode(196));
	s = s.replace("&Ouml;", String.fromCharCode(214));
	s = s.replace("&Uuml;", String.fromCharCode(220));
	s = s.replace("&auml;", String.fromCharCode(228));
	s = s.replace("&ouml;", String.fromCharCode(246));
	s = s.replace("&uuml;", String.fromCharCode(252));
	s = s.replace("&szlig;", String.fromCharCode(223));
	s = s.replace("&amp;", String.fromCharCode(38));
	return s;
}

function addThousandSeparators(s) {
	//given 12345, returns 12.345
	var e=3;
	var sep=".";
	var l=s.length;
	if (l<=e) { return s; }
	if (l<=2*e) {return (s.substr(0,l-e)+sep+s.substr(l-e));}
	if (l<=3*e) {return (s.substr(0,l-2*e)+sep+s.substr(l-2*e,e)+sep+s.substr(l-e,e));}
	return s;
}

/******************************** Cryptic add and remove event code ***************************/
var aeOL=[];function addEvent(o,n,f,l){
	var a='addEventListener',h='on'+n,b='',s='';
	if(o[a]&&!l)return o[a](n,f,false);
	o._c|=0;
	if(o[h]){
		b='_f'+o._c++;o[b]=o[h]
	}
	s='_f'+o._c++;
	o[s]=f;o[h]=function(e){
		e=e||window.event;var r=true;if(b)r=o[b](e)!=false&&r;r=o[s](e)!=false&&r;return r
	};
	aeOL[aeOL.length]={o:o,h:h}
};
addEvent(window,'unload',function(){
	for(var i=0;i<aeOL.length;i++)with(aeOL[i]){
		o[h]=null;for(var c=0;o['_f'+c];c++)o['_f'+c]=null
	}
}
);

function cancelEvent(e,c){
	e.returnValue=false;if(e.preventDefault)e.preventDefault();
	if(c){
		e.cancelBubble=true;if(e.stopPropagation)e.stopPropagation()
	}
};

/******************************** toggling ***************************/



function toggleInto(src, destId)
{
	dest=$(destId);
	if (src && dest)
	{
		if( dest.style) 
		{
			
		if (!dest.toggleState)
		{
			src.innerHTML = '<img class="toggle" src="http://static.poppen.de/siteimages/buttons/toggleclose.gif" title="toggle">';
			dest.style.display = 'block';
			dest.toggleState = 1;
			toggleFunctions(destId, dest.toggleState);
		}
		else
		{
			src.innerHTML = '<img class="toggle" src="http://static.poppen.de/siteimages/buttons/toggle.gif" title="toggle">';
			dest.style.display = 'none';
			dest.toggleState = 0;
			toggleFunctions(destId, dest.toggleState);
		}
		
	 }
	} 
}

function enableToggleButtons() {
addEvent(document, 'click', function(evt)
{
	// Here we capture all clicks on the document, scanning for links with a CLASS
	// attribute of "loadinto-IdOfTarget" and routing them to loadInto() above.
	evt = evt || window.event;
	var src = evt.target || evt.srcElement;
	if (src.nodeType && src.nodeType != 1) src = src.parentNode;
	// Loop up the DOM tree scanning all elements to find a matching one.
	while (src)
	{
		var srcName = (src.nodeName||src.tagName||'').toLowerCase();
		if (srcName == 'a' && src.className && src.className.match(/^(load|toggle)into-(.+)$/))
		{
			// Call our load handlers if we have a match; they'll cancel the normal action.
			if (RegExp.$1 == 'load') return loadInto(src, RegExp.$2, evt);
			if (RegExp.$1 == 'toggle') return toggleInto(src, RegExp.$2, evt);
		}
		src = src.parentNode;
	}
}, 1);
}

/******************************** popup windows ***************************/

var popUpWin = false;

function popUpWindow(URLStr, left, top, width, height)
{
	if(popUpWin)
	{
		if(!popUpWin.closed) popUpWin.close();
	}
	popUpWin = open(URLStr, 'popUpWin', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbar=no,resizable=no,copyhistory=yes,width='+width+',height='+height+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'');
}

function pop(url,target,left,top,width,height,resizable,scrollbars) {
	window.open(url,target,'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars='+(scrollbars==true?'yes':'no')+',resizable='+(resizable==true?'yes':'no')+',copyhistory=yes,width='+width+',height='+height+',left='+left+',top='+top+',screenX='+left+',screenY='+top+'');
	try {Session.update()} catch (e) {;}
}

function openProfilLinkByNicknameLoggedIn(nickName)
{
    url = "/profilserver/profil_" + nickName.toLowerCase() + ".html";
	  newwindow = window.open(url,nickName,"height=700,width=800,status=no,location=no,resizable=no,menubar=no,toolbar=no,scrollbars=yes");
    if (newwindow)newwindow.focus();
}

function openProfilLinkByNickname(nickName)
{
	if (window.logged || window.location.pathname=="/index2.php") {
    url = "/profilserver/profil_" + nickName.toLowerCase() + ".html";
	  newwindow = window.open(url,nickName,"height=700,width=800,status=no,location=no,resizable=no,menubar=no,toolbar=no,scrollbars=yes");
    if (newwindow)newwindow.focus();
  } else {
		alertanon();
		//poppenLoad('signup.php','iframe');
		parentLoadIntoDiv('signup.php');
	}
}

function openMyProfil(nickName)
{
	if (window.logged || window.location.pathname=="/index2.php") {
		var url = "/profilserver/myProfile.php?nickname=" + nickName.toLowerCase();
		window.open(url,"","height=700,width=800,status=no,location=no,resizable=no,menubar=no,toolbar=no,scrollbars=yes");
	} else {
		alertanon();
	}
}

function alertanon() {
	alert("Diese Funktion steht leider nur eingeloggten Mitgliedern zur Verf\374gung.\nFalls Du noch nicht angemeldet sein solltest, kannst Du Dich unter \"registrieren\" anmelden ."); return false;
}


/******************************** AJAX ***************************/
function AJAX(){
	//PRIVATE PROPERTIES
	var self=this;
	var xmlHttp;


	//PRIVATE FUNCTIONS
	function dispatch(url) {
		self.xmlHttp.open("GET", url, true);
		self.xmlHttp.send(null);
	}
	
	function justTheBody(doc) {
		var body_start=doc.indexOf('<body');
		var body_end=doc.indexOf('</body');
		if (body_start>-1 && body_end>-1) {
			var body_start_close=doc.indexOf('>',body_start);
			return (doc.substring(body_start_close+1,body_end));
		} else {
			return doc;
		}
	}

	function createRequestObject()
	{
		if(window.XMLHttpRequest)
		{
			return new XMLHttpRequest();
		}
		else if (window.ActiveXObject)
		{
			var versions = ["Msxml2.XMLHTTP.7.0", "Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
			for(var idx=0; idx < versions.length; idx++)
			{
				try
				{
					return new ActiveXObject(versions[idx]);
				}
				catch(objException)
				{
					;
				}
			}
		}
	}

	function ready() {
		return ((self.xmlHttp.readyState == 4) && (self.xmlHttp.status == 200));
	}

	function dumpInto(targetElement)
	{
		var txt=justTheBody(self.xmlHttp.responseText);
		if(txt.indexOf("<nil/>") == -1)
		{
			if (targetElement) {targetElement.innerHTML = txt;}
		}
	}


	//PRIVILEGED METHODS
	this.loadIntoElement= function(url, targetElement,callbackFunction) {
		self.xmlHttp=createRequestObject();
		self.xmlHttp.onreadystatechange = function()
		{
			if (ready()) {
				dumpInto(targetElement);
				if (callbackFunction) {callbackFunction(justTheBody(self.xmlHttp.responseText));}
			}
		};

		dispatch(url);
	}

	this.loadIntoFunction=function(url,callbackFunction) {
		self.xmlHttp=createRequestObject();
		self.xmlHttp.onreadystatechange = function()
		{
			if (ready() && callbackFunction) {callbackFunction(self.xmlHttp.responseXML);}
		};
		dispatch(url);
	}

	this.load=function(url) {
		self.loadIntoFunction(url,null);
	}



}

function getTag(xmlObj,tagname) {
	var tagarray=(xmlObj.getElementsByTagName(tagname));
	if (tagarray && tagarray.length>0 && tagarray[0].firstChild)
	{
		return tagarray[0].firstChild.nodeValue;
	}
	else
	{
		return null;
	}
}

/****************** querystring *****************/
/* Client-side access to querystring name=value pairs
	Version 1.2.3
	22 Jun 2005
	Adam Vandenberg
*/
function Querystring(qs) { // optionally pass a querystring to parse
	this.params = new Object()
	this.get=Querystring_get
	
	if (qs == null)
		qs=location.search.substring(1,location.search.length)

	if (qs.length == 0) return

// Turn <plus> back to <space>
// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ')
	var args = qs.split('&') // parse out name/value pairs separated via &
	
// split out each name=value pair
	for (var i=0;i<args.length;i++) {
		var value;
		var pair = args[i].split('=')
		var name = unescape(pair[0])

		if (pair.length == 2)
			value = unescape(pair[1])
		else
			value = name
		
		this.params[name] = value
	}
}

function Querystring_get(key, default_) {
	if (default_ == null) default_ = null;
	
	var value=this.params[key]
	if (value==null) value=default_;
	
	return value
}



function parentLoad(page) {
	try {
		//popped up from iframe
		window.opener.parent.poppenLoad(page,'iframe');
		window.close();
	} catch (e) {
		try {
			//popped up from main page
			window.opener.poppenLoad(page,'iframe');
			window.close();
		} catch (e2) {
			//must be in our own browser window
			window.location="/index.html?iframe="+page;			
		}
	}	
}

function parentLoadIntoDiv(page) {
	try {
		//popped up from iframe
		window.opener.parent.location="/index2.php?div="+page;
		//window.close();
	} catch (e) {
		try {
			//popped up from main page
			window.opener.location="/index2.php?div="+page;
			window.close();
		} catch (e2) {
			//must be in our own browser window
			window.location=location="/index2.php?div="+page;			
		}
	}	
}

